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());

三、测试结果

相关推荐
莱茵菜苗11 分钟前
Python打卡训练营day46——2025.06.06
开发语言·python
爱学习的小道长13 分钟前
Python 构建法律DeepSeek RAG
开发语言·python
luojiaao40 分钟前
【Python工具开发】k3q_arxml 简单但是非常好用的arxml编辑器,可以称为arxml杀手包
开发语言·python·编辑器
终焉代码41 分钟前
STL解析——list的使用
开发语言·c++
SoFlu软件机器人43 分钟前
智能生成完整 Java 后端架构,告别手动编写 ControllerServiceDao
java·开发语言·架构
英英_1 小时前
视频爬虫的Python库
开发语言·python·音视频
猛犸MAMMOTH1 小时前
Python打卡第46天
开发语言·python·机器学习
多多*1 小时前
微服务网关SpringCloudGateway+SaToken鉴权
linux·开发语言·redis·python·sql·log4j·bootstrap
梓仁沐白1 小时前
【Kotlin】协程
开发语言·python·kotlin
Java Fans2 小时前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf