当前位置:   article > 正文

redisson 使用fastJson2序列化_redisson fastjson

redisson fastjson

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

一、自定义序列化器

  1. import com.alibaba.fastjson2.JSON;
  2. import com.alibaba.fastjson2.JSONReader;
  3. import com.alibaba.fastjson2.JSONWriter;
  4. import io.netty.buffer.ByteBuf;
  5. import io.netty.buffer.ByteBufAllocator;
  6. import io.netty.buffer.ByteBufInputStream;
  7. import io.netty.buffer.ByteBufOutputStream;
  8. import org.redisson.client.codec.Codec;
  9. import org.redisson.client.codec.StringCodec;
  10. import org.redisson.client.handler.State;
  11. import org.redisson.client.protocol.Decoder;
  12. import org.redisson.client.protocol.Encoder;
  13. import org.redisson.codec.JsonJacksonCodec;
  14. import org.springframework.http.codec.json.Jackson2JsonDecoder;
  15. import org.springframework.http.codec.json.Jackson2SmileDecoder;
  16. import java.io.IOException;
  17. import java.nio.charset.Charset;
  18. /**
  19. * @author yh
  20. */
  21. public class FastJson2JsonRedissonSerializer extends StringCodec {
  22. public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  23. private final Encoder encoder = new Encoder() {
  24. @Override
  25. public ByteBuf encode(Object in) throws IOException {
  26. ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
  27. try {
  28. ByteBufOutputStream os = new ByteBufOutputStream(out);
  29. JSON.writeTo(os, in, JSONWriter.Feature.WriteClassName);
  30. // return JSON.toJSONBytes(in, JSONWriter.Feature.WriteClassName);
  31. return os.buffer();
  32. } catch (Exception e) {
  33. out.release();
  34. throw new IOException(e);
  35. }
  36. }
  37. };
  38. private final Decoder<Object> decoder = new Decoder<Object>() {
  39. @Override
  40. public Object decode(ByteBuf buf, State state) throws IOException {
  41. return JSON.parseObject(new ByteBufInputStream(buf), Object.class, JSONReader.Feature.SupportAutoType);
  42. }
  43. };
  44. @Override
  45. public Decoder<Object> getValueDecoder() {
  46. return decoder;
  47. }
  48. @Override
  49. public Encoder getValueEncoder() {
  50. return encoder;
  51. }
  52. }

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

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

三、测试结果

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/897317
推荐阅读
相关标签
  

闽ICP备14008679号