Fork me on GitHub

SignalR 中使用 MessagePack 序列化提高 WebSocket 通信性能

It's like JSON.
but fast and small.

MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it's faster and smaller. Small integers are encoded into a single byte, and typical short strings require only one extra byte in addition to the strings themselves.

默认我们在 ASP.NET Core SignalR 中使用 WebSocket 协议通信,默认使用 JSON 格式数据传输,为了更高效我们可以使用 MessagePack 来替换。 MessagePack 是一个高效的二进制序列化格式。它让你像JSON一样可以在各种语言之间交换数据。但是它比JSON更快、更小。小的整数会被编码成一个字节,短的字符串仅仅只需要比它的长度多一字节的大小。

在 SignalR 中使用 MessagePack 也很简单:

复制代码
public void ConfigureServices(IServiceCollection services)
        {
            //自定义配置
            services.Configure<DbSetting>(Configuration.GetSection("ConnectionStrings"));

            //https://docs.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-2.1
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //添加 Hangfire 服务
            services.AddHangfire(config => config.UseRedisStorage(Redis));
            // services.AddHangfire(config => config.UseSqlServerStorage("<connection string>"));

            //添加 Cookie 中间件
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                // sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })

            //.AddAzureAdB2C(opts => Configuration.Bind("AzureAdB2C", opts))
            .AddCookie(opts =>
            {
                opts.LoginPath = new PathString("/account/login");
                opts.AccessDeniedPath = new PathString("/account/denied");
            });

            services.AddSignalR(options =>
            {
                //Faster pings for testing
                //options.KeepAliveInterval = TimeSpan.FromSeconds(5);
            })
            .AddMessagePackProtocol(options =>
            {
               // options.FormatterResolvers = new List<MessagePack.IFormatterResolver>()
                //{
                 //   MessagePack.Resolvers.StandardResolver.Instance
                //};
            })
            .AddRedis(Configuration.GetConnectionString("Redis"));

            //返回大小写问题
            services.AddMvc()
                    .AddJsonOptions(option => option.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());
        }
复制代码
.NET 客户端
var hubConnection = new HubConnectionBuilder()
                        .WithUrl("/chatHub")
                        .AddMessagePackProtocol()
                        .Build();

JavaScript 客户端

npm install @aspnet/signalr-protocol-msgpack
<script src="~/lib/signalr/signalr.js"></script>
<script src="~/lib/msgpack5/msgpack5.js"></script>
<script src="~/lib/signalr/signalr-protocol-msgpack.js"></script>
const connection = new signalR.HubConnectionBuilder()
                              .withUrl("/hqHub")
                              .withHubProtocol(new signalR.protocols.msgpack.MessagePackHubProtocol())
                              .build();

运行日志

image

REFER:
https://docs.microsoft.com/en-us/aspnet/core/signalr/messagepackhubprotocol?view=aspnetcore-2.1
https://damienbod.com/2018/03/19/using-message-pack-with-asp-net-core-signalr/
https://socket.io/docs/

posted @   花儿笑弯了腰  阅读(2853)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示