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

news2025/5/12 0:29:43

📊 结合 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

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


十、参考链接 🔗📚

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2373540.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

快速上手 Docker:从入门到安装的简易指南(Mac、Windows、Ubuntu)

PS&#xff1a;笔者在五一刚回来一直搞Docker部署AI项目&#xff0c;发现从开发环境迁移到生成环境时&#xff0c;Docker非常好用。但真的有一定上手难度&#xff0c;推荐读者多自己尝试踩踩坑。 本篇幅有限&#xff0c;使用与修改另起篇幅。 一、Docker是什么 #1. Docker是什…

MySQL + Elasticsearch:为什么要使用ES,使用场景与架构设计详解

MySQL Elasticsearch&#xff1a;为什么要使用ES&#xff0c;使用场景与架构设计详解 前言一、MySQL Elasticsearch的背景与需求1.1 为什么要使用Elasticsearch&#xff08;ES&#xff09;&#xff1f;1.2 为什么MySQL在某些场景下不足以满足需求&#xff1f;1.3 MySQL Elas…

从投入产出、效率、上手难易度等角度综合对比 pytest 和 unittest 框架

对于选择python作为测试脚本开发的同学来说&#xff0c;pytest和python unittest是必需了解的两个框架。那么他们有什么区别&#xff1f;我们该怎么选&#xff1f;让我们一起来了解一下吧&#xff01; 我们从投入产出、效率、上手难易度等角度综合对比 pytest 和 unittest 框架…

关于汇编语言与程序设计——单总线温度采集与显示的应用

一、实验要求 (1)握码管的使用方式 (2)掌握DS18B20温度传感器的工作原理 (3)掌握单总线通信方式实现 MCU与DS18B20数据传输 二、设计思路 1.整体思路 通过编写数码管显示程序和单总线温度采集程序&#xff0c;结合温度传感报警&#xff0c;利用手指触碰传感器&#xff0c;当…

spring中的@Inject注解详情

在 Spring 框架中&#xff0c;Inject 是 Java 依赖注入标准&#xff08;JSR-330&#xff09; 的核心注解&#xff0c;与 Spring 原生的 Autowired 类似&#xff0c;但具备更标准化的跨框架特性。以下从功能特性、使用场景及与 Spring 原生注解的对比进行详细解析&#xff1a; 一…

Vue基础(8)_监视属性、深度监视、监视的简写形式

监视属性(watch)&#xff1a; 1.当被监视的属性变化时&#xff0c;回调函数(handler)自动调用&#xff0c;进行相关操作。 2.监视的属性必须存在&#xff0c;才能进行监视&#xff01;&#xff01; 3.监视的两种写法&#xff1a; (1).new Vue时传入watch配置 (2).通过vm.$watc…

TCP IP

TCP/IP 通信协议&#xff0c;不是单一协议&#xff0c;是一组协议的集合 TCP IP UDP 1.建立链接 三次握手 第一步&#xff1a;客户端发送一个FIN报文&#xff0c;SEQX,等待服务器回应 第二步&#xff1a;服务器端受到&#xff0c;发送ackx1,seqy, 等待客户端回应 第三步&am…

(四)毛子整洁架构(Presentation层/Authentiacation/Authorization)

文章目录 项目地址一、Presentation 层1.1 数据库migration1. 添加数据库连接字符串2. 创建自动Migration/Seed3.修改Entity添加private 构造函数4. 执行迁移 1.2 全局错误处理中间件1.3 Controller 添加1. Apartments2. Bookings3. 测试 二、Authentiacation2.1 添加Keycloak服…

K8S服务的请求访问转发原理

开启 K8s 服务异常排障过程前&#xff0c;须对 K8s 服务的访问路径有一个全面的了解&#xff0c;下面我们先介绍目前常用的 K8s 服务访问方式&#xff08;不同云原生平台实现方式可能基于部署方案、性能优化等情况会存在一些差异&#xff0c;但是如要运维 K8s 服务&#xff0c;…

20250510解决NanoPi NEO core开发板在Ubuntu core22.04.3系统下适配移远的4G模块EC200A-CN的问题

1、h3-eflasher-friendlycore-jammy-4.14-armhf-20250402.img.gz 在WIN10下使用7-ZIP解压缩/ubuntu20.04下使用tar 2、Win32DiskImager.exe 写如32GB的TF卡。【以管理员身份运行】 3、TF卡如果已经做过会有3个磁盘分区&#xff0c;可以使用SD Card Formatter/SDCardFormatterv5…

Linux系统之----模拟实现shell

在前面一个阶段的学习中&#xff0c;我们已经学习了环境变量、进程控制等等一系列知识&#xff0c;也许有人会问&#xff0c;学这个东西有啥用&#xff1f;那么&#xff0c;今天我就和大家一起综合运用一下这些知识&#xff0c;模拟实现下shell&#xff01; 首先我们来看一看我…

TCP黏包解决方法

1. 问题描述 TCP客户端每100ms发送一次数据,每次为16006字节的数据长度。由于TCP传输数据时,为了达到最佳传输效能,数据包的最大长度需要由MSS限定(MSS就是TCP数据包每次能够传输的最大数据分段),超过这个长度会进行自动拆包。也就是说虽然客户端一次发送16006字节数据,…

vue访问后端接口,实现用户注册

文章目录 一、后端接口文档二、前端代码请求响应工具调用后端API接口页面函数绑定单击事件&#xff0c;调用/api/user.js中的函数 三、参考视频 一、后端接口文档 二、前端代码 请求响应工具 /src/utils/request.js //定制请求的实例//导入axios npm install axios import …

Nginx性能调优与深度监控

目录 1更改进程数与连接数 &#xff08;1&#xff09;进程数 &#xff08;2&#xff09;连接数 2&#xff0c;静态缓存功能设置 &#xff08;1&#xff09;设置静态资源缓存 &#xff08;2&#xff09;验证静态缓存 3&#xff0c;设置连接超时 4&#xff0c;日志切割 …

如何在大型项目中解决 VsCode 语言服务器崩溃的问题

在大型C/C项目中&#xff0c;VS Code的语言服务器&#xff08;如C/C扩展&#xff09;可能因内存不足或配置不当频繁崩溃。本文结合系统资源分析与实战技巧&#xff0c;提供一套完整的解决方案。 一、问题根源诊断 1.1 内存瓶颈分析 通过top命令查看系统资源使用情况&#xff…

AutoDL实现端口映射与远程连接AutoDL与Pycharm上传文件到远程服务器(李沐老师的环境)

文章目录 以上配置的作用前提AutoDL实现端口映射远程连接AutoDLPycharm上传文件到远程服务器以上配置的作用 使用AutoDL的实例:因本地没有足够强的算力,所以需要使用AutoDL AutoDL端口映射:当在实例上安装深度学习的环境,但因为实例的linux系统问题,无法图形化显示d2l中的文件…

13.thinkphp的Session和cookie

一&#xff0e;Session 1. 在使用Session之前&#xff0c;需要开启初始化&#xff0c;在中间件文件middleware.php&#xff1b; // Session 初始化 \think\middleware\SessionInit::class 2. TP6.0不支持原生$_SESSION的获取方式&#xff0c;也不支持session_开头的函数&…

多线程获取VI模块的YUV数据

一.RV1126 VI模块采集摄像头YUV数据的流程 step1&#xff1a;VI模块初始化 step2&#xff1a;启动VI模块工作 step3&#xff1a;开启多线程采集VI数据并保存 1.1初始化VI模块&#xff1a; VI模块的初始化实际上就是对VI_CHN_ATTR_S的参数进行设置、然后调用RK_MPI_VI_SetC…

[ctfshow web入门] web68

信息收集 highlight_file被禁用了&#xff0c;使用cinclude("php://filter/convert.base64-encode/resourceindex.php");读取index.php&#xff0c;使用cinclude("php://filter/convert.iconv.utf8.utf16/resourceindex.php");可能有些乱码&#xff0c;不…

16前端项目----交易页

交易 交易页Trade修改默认地址商品清单reduce计算总数和总价应用 统一引入接口提交订单 交易页Trade 在computed中mapState映射出addressInfo和orderInfo&#xff0c;然后v-for渲染到组件当中 修改默认地址 <div class"address clearFix" v-for"address in …