结合 ECharts / Ant Design Blazor 构建高性能实时仪表盘

结合 ECharts / Ant Design Blazor 构建高性能实时仪表盘


目录

  • 结合 ECharts / Ant Design Blazor 构建高性能实时仪表盘
    • 一、前言
    • 二、技术选型
    • 三、项目配置与架构 ️
      • 系统整体架构流程图
      • Program.cs
      • _Host.cshtml
    • 四、数据模型与推送服务 ➡️
      • ChartData.cs
      • IDataPushService.cs
      • DataPushService.cs
      • 数据推送流程图
      • DashboardHub.cs
    • 五、后台数据推送服务 ⏰
      • TimedPushService.cs
    • 六、封装图表组件与 JS 模块 ️
      • EChart.razor
      • echarts-helper.js
      • ️ 图表初始化与更新流程图
    • 七、仪表盘页面 Dashboard.razor ️‍
      • SignalR 连接生命周期流程图
    • 八、部署与运行 ⚙️
      • ⚙️ 部署与运行流程图
    • 九、总结 ✨
    • 十、参考链接


一、前言

在现代 Web 应用中,数据可视化尤为重要,特别是在物联网、金融风控、数据运营等领域,实时仪表盘成为监控系统的核心组成部分。本文将介绍如何结合 ECharts 和 Ant Design Blazor 构建一个具备自动重连、节流更新⏱️、高性能渲染⚡的实时数据仪表盘系统。


二、技术选型

推荐版本:

  • ECharts ^5.4.0

  • Ant Design Blazor ^2.2.0

  • ASP.NET Core SignalR >=7.0

  • ECharts:百度开源的图表库,功能丰富、性能优异,适合构建各种复杂图表。

  • Ant Design Blazor:阿里开源的 Ant Design 在 Blazor 平台上的实现,提供现代化、高颜值组件✨。

  • SignalR:用于实现浏览器端 WebSocket 式实时推送。


三、项目配置与架构 ️

系统整体架构流程图

Server
Client
Dashboard 页面
Dashboard.razor
浏览器
EChart 组件
SignalR 客户端
SignalR Hub
Program.cs 配置服务
Ant Design Blazor
后台定时推送服务
TimedPushService
DataPushService
SCLL

Program.cs

// Program.cs
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using RealTimeDashboard.Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddAntDesign();

builder.Services.AddSignalR()
    .AddJsonProtocol(options =>
    {
        // 输出 camelCase,以配合 JS 客户端常用习惯
        options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    });

builder.Services.AddSingleton<IDataPushService, DataPushService>();
builder.Services.AddHostedService<TimedPushService>();

var app = builder.Build();

app.UseStaticFiles();
app.UseRouting();
app.UseAntDesign();

app.MapBlazorHub();
app.MapHub<DashboardHub>("/dashboardHub");
app.MapFallbackToPage("/_Host");

app.Run();

_Host.cshtml


DOCTYPE html>
<html>
<head>
    <base href="~/" />
    <meta charset="utf-8" />
    <title>实时仪表盘 - MyBlazorApptitle>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="description" content="使用 Blazor + ECharts + SignalR 构建实时数据仪表盘,支持自动重连、节流更新与高性能渲染。" />
    <meta name="keywords" content="Blazor, ECharts, SignalR, 实时仪表盘, Ant Design Blazor, 可视化, .NET" />
    <link rel="stylesheet" href="~/_content/AntDesign/css/ant-design-blazor.css" />
    <script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js">script>
head>
<body>
    <app>
        <component type="typeof(App)" render-mode="ServerPrerendered" />
    app>
    <script src="_framework/blazor.server.js">script>
body>
html>

四、数据模型与推送服务 ➡️

ChartData.cs

// Models/ChartData.cs
namespace RealTimeDashboard.Models
{
    public record ChartData(string[] XAxis, int[] Values);
}

IDataPushService.cs

// Services/IDataPushService.cs
using System.Threading.Tasks;
using RealTimeDashboard.Models;

namespace RealTimeDashboard.Services
{
    public interface IDataPushService
    {
        Task PushAsync(ChartData data);
    }
}

DataPushService.cs

// Services/DataPushService.cs
using Microsoft.AspNetCore.SignalR;
using RealTimeDashboard.Hubs;
using RealTimeDashboard.Models;

namespace RealTimeDashboard.Services
{
    public class DataPushService : IDataPushService
    {
        private readonly IHubContext<DashboardHub> _hubContext;
        public DataPushService(IHubContext<DashboardHub> hubContext) => _hubContext = hubContext;

        public Task PushAsync(ChartData data)
            => _hubContext.Clients.All.SendAsync("updateChart", data);
    }
}

数据推送流程图

生成 ChartData 实例
调用 IDataPushService.PushAsync(data)
HubContext.SendAsync('updateChart', data)
SignalR Clients.All 广播
客户端 On('updateChart') 收到数据
更新 chartOption 并触发 StateHasChanged()

DashboardHub.cs

// Hubs/DashboardHub.cs
using Microsoft.AspNetCore.SignalR;

namespace RealTimeDashboard.Hubs
{
    public class DashboardHub : Hub { }
}

五、后台数据推送服务 ⏰

TimedPushService.cs

// Services/TimedPushService.cs
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RealTimeDashboard.Models;

namespace RealTimeDashboard.Services
{
    public class TimedPushService : BackgroundService
    {
        private readonly IDataPushService _push;
        private readonly ILogger<TimedPushService> _logger;

        public TimedPushService(IDataPushService push, ILogger<TimedPushService> logger)
        {
            _push = push;
            _logger = logger;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var xAxis = new[] { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
            var rnd = Random.Shared;

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    var data = new ChartData(
                        xAxis,
                        Enumerable.Range(0, 7)
                                  .Select(_ => rnd.Next(800, 1400))
                                  .ToArray()
                    );
                    await _push.PushAsync(data);
                    // 加入少量随机抖动,避免集中重连
                    await Task.Delay(3000 + rnd.Next(0, 500), stoppingToken);
                }
                catch (TaskCanceledException)
                {
                    // 服务停止时忽略
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "数据推送异常");
                }
            }
        }
    }
}

六、封装图表组件与 JS 模块 ️

EChart.razor


@inject IJSRuntime JSRuntime
@implements IAsyncDisposable

@code { [Parameter] public string ChartId { get; set; } = $"chart-{Guid.NewGuid()}"; [Parameter] public object? ChartOptions { get; set; } [Parameter] public int ThrottleMs { get; set; } = 200; private IJSObjectReference? _module; protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender && ChartOptions is not null) { _module = await JSRuntime.InvokeAsync( "import", "/js/echarts-helper.js" ); await _module.InvokeVoidAsync("initChart", ChartId, ChartOptions, ThrottleMs); } } protected override async Task OnParametersSetAsync() { if (_module is not null && ChartOptions is not null) { await _module.InvokeVoidAsync("updateChart", ChartId, ChartOptions); } } public async ValueTask DisposeAsync() { if (_module is not null) { await _module.InvokeVoidAsync("disposeChart", ChartId); await _module.DisposeAsync(); } } }

echarts-helper.js

// wwwroot/js/echarts-helper.js
window.__charts = {};
const throttleConfigs = {};
const throttleTimers = {};

if (!window.__chartsResizeRegistered) {
  window.addEventListener("resize", () => {
    Object.values(window.__charts).forEach(chart => chart.resize());
  });
  window.__chartsResizeRegistered = true;
}

export function initChart(id, options, throttleMs = 200) {
  const container = document.getElementById(id);
  if (!container) return;
  const chart = echarts.init(container);
  chart.setOption(options);
  window.__charts[id] = chart;
  throttleConfigs[id] = throttleMs;
}

export function updateChart(id, options) {
  clearTimeout(throttleTimers[id]);
  throttleTimers[id] = setTimeout(() => {
    window.__charts[id].setOption(options, { notMerge: true, lazyUpdate: true });
  }, throttleConfigs[id]);
}

export function disposeChart(id) {
  if (window.__charts[id]) {
    window.__charts[id].dispose();
    delete window.__charts[id];
  }
  delete throttleConfigs[id];
  clearTimeout(throttleTimers[id]);
  delete throttleTimers[id];
}

️ 图表初始化与更新流程图

资源释放
执行 chart.dispose()
调用 disposeChart(id)
删除 window.__charts[id] 和 定时器
初始化 initChart(id, options)
查找 DOM 容器 并 调用 echarts.init()
调用 chart.setOption(options)
保存至 window.__charts[id]
触发 updateChart(id, options)
节流后 再次 调用 chart.setOption(...)

七、仪表盘页面 Dashboard.razor ️‍


@page "/dashboard"
@using RealTimeDashboard.Components
@using RealTimeDashboard.Models
@using Microsoft.AspNetCore.SignalR.Client
@inject NavigationManager Navigation
@inject IJSRuntime JSRuntime
@inject MessageService Message
@implements IAsyncDisposable

实时仪表盘

@code { private HubConnection? _conn; private EChart? chartRef; private object chartOption = new { xAxis = new { type = "category", data = new[] { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" } }, yAxis = new { type = "value" }, series = new[] { new { data = new[] { 820, 932, 901, 934, 1290, 1330, 1320 }, type = "line" } } }; protected override async Task OnInitializedAsync() { _conn = new HubConnectionBuilder() .WithUrl(Navigation.ToAbsoluteUri("/dashboardHub")) .WithAutomaticReconnect() .Build(); _conn.On("updateChart", data => { chartOption = new { xAxis = new { type = "category", data = data.XAxis }, yAxis = new { type = "value" }, series = new[] { new { data = data.Values, type = "line" } } }; InvokeAsync(StateHasChanged); }); _conn.Closed += error => { _ = Message.Error("SignalR 连接已断开"); return Task.CompletedTask; }; _conn.Reconnected += id => { _ = Message.Success("SignalR 已重连"); return Task.CompletedTask; }; try { await _conn.StartAsync(); } catch (Exception ex) { Message.Error($"SignalR 连接失败:{ex.Message}"); } } public async ValueTask DisposeAsync() { if (_conn is not null) await _conn.DisposeAsync(); if (chartRef is not null) await chartRef.DisposeAsync(); } }

SignalR 连接生命周期流程图

资源清理
conn.DisposeAsync()
组件销毁
DisposeAsync()
chartRef.DisposeAsync()
组件初始化
OnInitializedAsync()
构建 HubConnectionBuilder
启用 自动重连
WithAutomaticReconnect()
调用 StartAsync()
注册 On 回调
更新 UI
调用 InvokeAsync(StateHasChanged())
连接断开 Closed →
Message.Error()
重连成功 Reconnected →
Message.Success()

八、部署与运行 ⚙️

  1. 安装 Ant Design Blazor 静态资源工具 ️
   dotnet tool install -g AntDesign.Cli
  1. 确保基础路径
    _Host.cshtml 中已添加
  2. 静态文件位置 ️
    确保 wwwroot/js/echarts-helper.js 已正确复制到项目中。
  3. **启动项目 **
   dotnet run

浏览器访问 https://localhost:5001/dashboard 即可查看实时仪表盘 ✅。

⚙️ 部署与运行流程图

安装 Ant Design CLI
dotnet tool install -g AntDesign.Cli
检查 base href
_Host.cshtml
复制 echarts-helper.js
到 wwwroot/js
dotnet run 启动服务
浏览器访问
https://localhost:5001/dashboard

九、总结 ✨

本文完整演示了如何通过 Blazor Server️、ECharts 和 SignalR 构建一个高性能⚡、自动重连、支持节流⏳和资源释放的实时仪表盘系统。所有模块均已封装✅、可复用,并遵循生产级最佳实践,适合在真实项目中直接采用或扩展。


十、参考链接

  • ECharts 官方文档
  • Ant Design Blazor
  • SignalR 官方文档
  • Blazor Server 文档

你可能感兴趣的:(Abp,vNext,.net,echarts,前端,javascript,.net,c#)