【问题标题】:How to enable LZ4 compression for messagepack content type in Asp.net Core Web API如何在 Asp.net Core Web API 中为消息包内容类型启用 LZ4 压缩
【发布时间】:2019-02-12 22:21:01
【问题描述】:

我正在尝试在我正在处理的 .net Core Web API 项目上启用 MessagePack 内容类型。

经过一番研究,安装了这个nuget 包并在启动文件中添加了以下代码。很容易!现在我可以看到通过我的 API 提供的 msgpack 内容。

services.AddMvc().AddMessagePackFormatters(c => 
{
  c.FormatterResolver = ContractlessStandardResolver.Instance;
  c.SupportedContentTypes.Add("application/x-msgpack");
  c.SupportedExtensions.Add("mp");
});

现在我想在它上面应用 LZ4 压缩来减少 here 中提到的有效负载大小。而且我找不到任何 nuget 包来添加此功能或找出插件 LZ4 压缩的方法。在一些博客中,我读到 LZ4 压缩是内置在 MessagePack 中的。我不明白这意味着什么,而且关于这些东西的文档很少。

我是压缩/解压缩方面的新手,因此感谢您提供任何帮助。

谢谢

【问题讨论】:

    标签: asp.net-core asp.net-core-webapi msgpack lz4


    【解决方案1】:

    您必须编写自定义媒体类型格式化程序,因为压缩是在不同的模块中使用的。您必须使用LZ4MessagePackSerializer 而不是MessagePackSerializer。用法是一样的。另外推荐的 MIME 类型是application/msgpack

    查看这个基本示例:

        public class MsgPackMediaTypeFormatter: BufferedMediaTypeFormatter
        {
            public MsgPackMediaTypeFormatter()
            {
                SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/msgpack"));
            }
    
            public override bool CanReadType(Type type)
            {
                return !type.IsAbstract && !type.IsInterface && type.IsPublic;
            }
    
            public override bool CanWriteType(Type type)
            {
                return !type.IsAbstract && !type.IsInterface && type.IsPublic;
            }
    
            public override object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
            {
                return LZ4MessagePackSerializer.NonGeneric.Deserialize(type, readStream);
            }
    
            public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)
            {
                LZ4MessagePackSerializer.NonGeneric.Serialize(type, writeStream, value, MessagePack.Resolvers.ContractlessStandardResolver.Instance);
            }
        }
    

    【讨论】:

    • 这正是我所做的!感谢您的回答。
    猜你喜欢
    • 2016-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-19
    • 2011-04-17
    • 2014-05-08
    相关资源
    最近更新 更多