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

三、测试结果

相关推荐
new_dev16 小时前
Python实现Android自动化打包工具:加固、签名、多渠道一键完成
android·python·自动化
_日拱一卒16 小时前
LeetCode:114二叉树展开为链表
java·开发语言·算法
天天进步201516 小时前
从零打造 Python 全栈项目:智能教学辅助系统
开发语言·人工智能·python
kkeeper~16 小时前
0基础C语言积跬步之内存函数
c语言·开发语言
吃好睡好便好16 小时前
在Matlab中绘制杆状图
开发语言·学习·算法·matlab·信息可视化
带带弟弟学爬虫__16 小时前
dyAPP数据采集-个人主页、发布、搜索、评论
服务器·python·算法·flutter·java-ee·django
还是鼠鼠16 小时前
AI掘金头条新闻系统 (Toutiao News)-相关推荐
后端·python·mysql·fastapi·web
桀人16 小时前
C++——内存管理——new和delete的超详细解析
开发语言·c++
Shadow(⊙o⊙)16 小时前
Shell进程替换,自定义Shell解释器——字符串库函数灵活操作!
linux·运维·服务器·开发语言·c++·学习
数智工坊16 小时前
PyCharm 运行 Python 脚本总自动进 Test 模式?附 RT-DETRv2 依赖缺失终极排坑
开发语言·ide·人工智能·python·pycharm