FastJson2JsonRedisSerializer.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package com.xtd.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 xtd
  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. public byte[] serialize(T t) throws SerializationException
  33. {
  34. if (t == null)
  35. {
  36. return new byte[0];
  37. }
  38. return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
  39. }
  40. public T deserialize(byte[] bytes) throws SerializationException
  41. {
  42. if (bytes == null || bytes.length <= 0)
  43. {
  44. return null;
  45. }
  46. String str = new String(bytes, DEFAULT_CHARSET);
  47. return JSON.parseObject(str, clazz);
  48. }
  49. public void setObjectMapper(ObjectMapper objectMapper)
  50. {
  51. Assert.notNull(objectMapper, "'objectMapper' must not be null");
  52. this.objectMapper = objectMapper;
  53. }
  54. protected JavaType getJavaType(Class<?> clazz)
  55. {
  56. return TypeFactory.defaultInstance().constructType(clazz);
  57. }
  58. }