redisson 使用fastJson2序列化

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

一、自定义序列化器

java 复制代码
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)

java 复制代码
// 创建fastjson的Redisson序列化器
 config.setCodec(new FastJson2JsonRedissonSerializer());

三、测试结果

相关推荐
lili-felicity6 分钟前
CANN性能调优与实战问题排查:从基础优化到排障工具落地
开发语言·人工智能
独自破碎E8 分钟前
【BISHI15】小红的夹吃棋
android·java·开发语言
进阶小白猿20 分钟前
Java技术八股学习Day33
java·开发语言·学习
历程里程碑1 小时前
普通数组----合并区间
java·数据结构·python·算法·leetcode·职场和发展·tornado
weixin_395448911 小时前
mult_yolov5_post_copy.c_cursor_0205
c语言·python·yolo
执风挽^1 小时前
Python基础编程题2
开发语言·python·算法·visual studio code
Z9fish1 小时前
sse哈工大C语言编程练习20
c语言·开发语言·算法
纤纡.2 小时前
PyTorch 入门精讲:从框架选择到 MNIST 手写数字识别实战
人工智能·pytorch·python
kjkdd2 小时前
6.1 核心组件(Agent)
python·ai·语言模型·langchain·ai编程
小镇敲码人2 小时前
剖析CANN框架中Samples仓库:从示例到实战的AI开发指南
c++·人工智能·python·华为·acl·cann