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

#王者杯·14天创作挑战营·第1期#

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



一、前言 🔍

在现代 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

<!-- _Host.cshtml -->
<!DOCTYPE html>
<html>
<head>
    <base href="~/" />
    <meta charset="utf-8" />
    <title>实时仪表盘 - MyBlazorApp</title>
    <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

<!-- Components/EChart.razor -->
@inject IJSRuntime JSRuntime
@implements IAsyncDisposable

<div id="@ChartId" style="width:100%;height:400px;"></div>

@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<IJSObjectReference>(
                "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 🎛️🧑‍💻

<!-- Pages/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

<h3>📈 实时仪表盘</h3>
<EChart @ref="chartRef" ChartId="mainChart" ChartOptions="chartOption" ThrottleMs="300" />

@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<ChartData>("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 <head> 中已添加 <base href="~/" />
  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📡 构建一个高性能⚡、自动重连🔁、支持节流⏳和资源释放🧹的实时仪表盘系统。所有模块均已封装✅、可复用🔁,并遵循生产级最佳实践🏆,适合在真实项目中直接采用🚀或扩展🧩。


十、参考链接 🔗📚

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kookoos

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值