赞
踩
前因:一个项目:有人用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());
三、测试结果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。