PageRenderTime 56ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/src/main/java/com/ruoyi/framework/config/FastJson2JsonRedisSerializer.java

https://gitlab.com/mrsunchangemyselfsun/ruoyi-vue
Java | 71 lines | 55 code | 11 blank | 5 comment | 5 complexity | af9fe8c50426f1a14bea972d61122370 MD5 | raw file
  1. package com.ruoyi.framework.config;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.serializer.SerializerFeature;
  4. import com.fasterxml.jackson.databind.JavaType;
  5. import com.fasterxml.jackson.databind.ObjectMapper;
  6. import com.fasterxml.jackson.databind.type.TypeFactory;
  7. import org.springframework.data.redis.serializer.RedisSerializer;
  8. import org.springframework.data.redis.serializer.SerializationException;
  9. import com.alibaba.fastjson.parser.ParserConfig;
  10. import org.springframework.util.Assert;
  11. import java.nio.charset.Charset;
  12. /**
  13. * Redis使用FastJson序列化
  14. *
  15. * @author ruoyi
  16. */
  17. public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
  18. {
  19. @SuppressWarnings("unused")
  20. private ObjectMapper objectMapper = new ObjectMapper();
  21. public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  22. private Class<T> clazz;
  23. static
  24. {
  25. ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
  26. }
  27. public FastJson2JsonRedisSerializer(Class<T> clazz)
  28. {
  29. super();
  30. this.clazz = clazz;
  31. }
  32. @Override
  33. public byte[] serialize(T t) throws SerializationException
  34. {
  35. if (t == null)
  36. {
  37. return new byte[0];
  38. }
  39. return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
  40. }
  41. @Override
  42. public T deserialize(byte[] bytes) throws SerializationException
  43. {
  44. if (bytes == null || bytes.length <= 0)
  45. {
  46. return null;
  47. }
  48. String str = new String(bytes, DEFAULT_CHARSET);
  49. return JSON.parseObject(str, clazz);
  50. }
  51. public void setObjectMapper(ObjectMapper objectMapper)
  52. {
  53. Assert.notNull(objectMapper, "'objectMapper' must not be null");
  54. this.objectMapper = objectMapper;
  55. }
  56. protected JavaType getJavaType(Class<?> clazz)
  57. {
  58. return TypeFactory.defaultInstance().constructType(clazz);
  59. }
  60. }