WeihanLi.Redis自定义序列化及压缩方式

时间:2023-03-10 00:21:04
WeihanLi.Redis自定义序列化及压缩方式

WeihanLi.Redis自定义序列化及压缩方式

Intro

WeihanLi.Redis 是基于 StackExchange.Redis 的扩展,提供了一些常用的业务组件和对泛型的更好支持,默认使用 JSON.Net 为基础的 JSON序列化,使用 GZip 进行数据压缩。

从 1.3.0 版本开始支持自定义序列化和压缩方式,下面介绍一下如何实现自定义序列化以及压缩。基本用法可以查看项目说明或这篇介绍

自定义序列化

自定义序列化只需要实现自己的 IDataSerializer 就可以了,用自己的序列化实现 IDataSerializer 接口,并注入服务即可(注:序列化器一个生命周期应当是 Singleton )。

Binary序列化的 BinaryDataSerializer 示例代码:

    public class BinaryDataSerializer : IDataSerializer
{
private readonly BinaryFormatter _binaryFormatter = new BinaryFormatter(); public T Deserializer<T>(byte[] bytes)
{
using (var memoryStream = new MemoryStream(bytes))
{
return (T)_binaryFormatter.Deserialize(memoryStream);
}
} public byte[] Serialize<T>(T obj)
{
using (var memoryStream = new MemoryStream())
{
_binaryFormatter.Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
}
    IServiceCollection services = new ServiceCollection();
services.AddRedisConfig(options => { });
// custom serializer
services.AddSingleton<IDataSerializer, BinaryDataSerializer>();
// set resolver
DependencyResolver.SetDependencyResolver(services);

WeihanLi.Common 中实现了三个序列化器,BinaryDataSerializer/XmlDataSerializer/JsonDataSerializer,可以参考 https://github.com/WeihanLi/WeihanLi.Common/blob/dev/src/WeihanLi.Common/Helpers/IDataSerializer.cs

自定义压缩

如果要使用自定义压缩,首先需要启用压缩,需要设置 EnableCompresstrue,然后注入自己的压缩方式,自定义压缩方式需要实现 IDataCompressor 接口,目前用到的只是同步方法,异步方法可以暂时不实现。

    IServiceCollection services = new ServiceCollection();
services.AddRedisConfig(options => { options.EnableCompress = true; });
// custom compressor
services.AddSingleton<IDataCompressor, MockDataCompressor>();
// set resolver
DependencyResolver.SetDependencyResolver(services);

MockDataCompressor 什么都没做,只是把数据原样返回了,并没有做处理,示例代码:

        publicclass MockDataCompressor : IDataCompressor
{
public byte[] Compress(byte[] sourceData)
{
return sourceData;
} public Task<byte[]> CompressAsync(byte[] sourceData)
{
return Task.FromResult(sourceData);
} public byte[] Decompress(byte[] compressedData)
{
return compressedData;
} public Task<byte[]> DecompressAsync(byte[] compressedData)
{
return Task.FromResult(compressedData);
}
}

Sample

这里提供一个示例项目,可以参考。

自定义序列化和压缩方式示例代码:


public static void Main(string[] args)
{
IServiceCollection services = new ServiceCollection();
services.AddRedisConfig(options => { options.EnableCompress = true; });
services.AddSingleton<IDataSerializer, BinaryDataSerializer>();
services.AddSingleton<IDataCompressor, MockDataCompressor>();
DependencyResolver.SetDependencyResolver(services); Console.ReadLine();
}

End

如果在使用过程中有遇到什么问题,欢迎与我联系,最近想大调整,为 .netstandard 重构一下,如果您有什么建议或者想法欢迎和我联系,多谢支持。