redisson 使用fastJson2序列化

前因:一个项目:有人用redisTemplete存数据(使用了fastjson2),使用redisson取的时候就会报错。要让redisTemplete与redisson序列化一致

一、自定义序列化器


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import org.redisson.client.codec.Codec;
import org.redisson.client.codec.StringCodec;
import org.redisson.client.handler.State;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;
import org.redisson.codec.JsonJacksonCodec;
import org.springframework.http.codec.json.Jackson2JsonDecoder;
import org.springframework.http.codec.json.Jackson2SmileDecoder;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author yh
 */
public class FastJson2JsonRedissonSerializer extends StringCodec {
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private final Encoder encoder = new Encoder() {
        @Override
        public ByteBuf encode(Object in) throws IOException {
            ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
            try {
                ByteBufOutputStream os = new ByteBufOutputStream(out);
                JSON.writeTo(os, in, JSONWriter.Feature.WriteClassName);
//                return JSON.toJSONBytes(in, JSONWriter.Feature.WriteClassName);
                return os.buffer();
            } catch (Exception e) {
                out.release();
                throw new IOException(e);
            }
        }
    };


    private final Decoder<Object> decoder = new Decoder<Object>() {

        @Override
        public Object decode(ByteBuf buf, State state) throws IOException {
            return JSON.parseObject(new ByteBufInputStream(buf), Object.class, JSONReader.Feature.SupportAutoType);
        }
    };

    @Override
    public Decoder<Object> getValueDecoder() {
        return decoder;
    }

    @Override
    public Encoder getValueEncoder() {
        return encoder;
    }

}

二、redsson 配置里添加自定义序列化器(RedissonConfiguration)

// 创建fastjson的Redisson序列化器
 config.setCodec(new FastJson2JsonRedissonSerializer());

三、测试结果

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值