📊 结合 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 式实时推送📡。
三、项目配置与架构 🏗️
🌐 系统整体架构流程图
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);
}
}
🔄 数据推送流程图
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];
}
🗂️ 图表初始化与更新流程图
七、仪表盘页面 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 连接生命周期流程图
八、部署与运行 ⚙️🚀
- 安装 Ant Design Blazor 静态资源工具 🛠️
dotnet tool install -g AntDesign.Cli
- 确保基础路径 🔗
在_Host.cshtml
<head>
中已添加<base href="~/" />
。 - 静态文件位置 🗂️
确保wwwroot/js/echarts-helper.js
已正确复制到项目中。 - **启动项目 **
dotnet run
浏览器访问 https://localhost:5001/dashboard
即可查看实时仪表盘 ✅。
⚙️ 部署与运行流程图
九、总结 📝✨
本文完整演示了如何通过 Blazor Server🖥️、ECharts📊 和 SignalR📡 构建一个高性能⚡、自动重连🔁、支持节流⏳和资源释放🧹的实时仪表盘系统。所有模块均已封装✅、可复用🔁,并遵循生产级最佳实践🏆,适合在真实项目中直接采用🚀或扩展🧩。