编解码

优质
小牛编辑
135浏览
2023-12-01

Uragano默认采用MessagePack编解码,你也可以通过实现ICodec接口自定义编解码

自定义编解码

public class MessagePackCodec : ICodec
    {
        public MessagePackCodec()
        {
            CompositeResolver.RegisterAndSetAsDefault(NativeDateTimeResolver.Instance, ContractlessStandardResolverAllowPrivate.Instance);
            MessagePackSerializer.SetDefaultResolver(ContractlessStandardResolverAllowPrivate.Instance);
        }

        public byte[] Serialize<TData>(TData data)
        {
            return MessagePackSerializer.Typeless.Serialize(data);
        }

        public object Deserialize(byte[] data, Type type)
        {
            return data == null ? null : MessagePackSerializer.Typeless.Deserialize(data);
        }

        public T Deserialize<T>(byte[] data)
        {
            return data == null ? default : (T)MessagePackSerializer.Typeless.Deserialize(data);
        }

        public string ToJson<TData>(TData data)
        {
            return data == null ? default : MessagePackSerializer.ToJson(data);
        }
    }

注入自定义编解码

service.AddUragano(context.Configuration, builder =>
                    {
                        builder.AddServer();
                        builder.AddConsul();
                        builder.AddCodec<MessagePackCodec>();
                    });