|
@@ -0,0 +1,73 @@
|
|
|
+package com.diagbot.config;
|
|
|
+
|
|
|
+import com.fasterxml.jackson.databind.JavaType;
|
|
|
+import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
+import com.fasterxml.jackson.databind.type.TypeFactory;
|
|
|
+import org.springframework.data.redis.serializer.RedisSerializer;
|
|
|
+import org.springframework.data.redis.serializer.SerializationException;
|
|
|
+import org.springframework.lang.Nullable;
|
|
|
+import org.springframework.util.Assert;
|
|
|
+import org.xerial.snappy.Snappy;
|
|
|
+
|
|
|
+import java.nio.charset.Charset;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @Description:
|
|
|
+ * @author: gaodm
|
|
|
+ * @time: 2021/12/15 15:29
|
|
|
+ */
|
|
|
+public class SnnpyJackson2JsonRedisSerializer<T> implements RedisSerializer<T> {
|
|
|
+ public static final Charset DEFAULT_CHARSET;
|
|
|
+ private final JavaType javaType;
|
|
|
+ private ObjectMapper objectMapper = new ObjectMapper();
|
|
|
+
|
|
|
+ static final byte[] EMPTY_ARRAY = new byte[0];
|
|
|
+
|
|
|
+ public SnnpyJackson2JsonRedisSerializer(Class<T> type) {
|
|
|
+ this.javaType = this.getJavaType(type);
|
|
|
+ }
|
|
|
+
|
|
|
+ public SnnpyJackson2JsonRedisSerializer(JavaType javaType) {
|
|
|
+ this.javaType = javaType;
|
|
|
+ }
|
|
|
+
|
|
|
+ public T deserialize(@Nullable byte[] bytes) throws SerializationException {
|
|
|
+ if (bytes == null || bytes.length == 0) {
|
|
|
+ return null;
|
|
|
+ } else {
|
|
|
+ try {
|
|
|
+ final byte[] uncompressBytes = Snappy.uncompress(bytes); //解压
|
|
|
+ return this.objectMapper.readValue(uncompressBytes, 0, uncompressBytes.length, this.javaType);
|
|
|
+ } catch (Exception var3) {
|
|
|
+ throw new SerializationException("Could not read JSON: " + var3.getMessage(), var3);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public byte[] serialize(@Nullable Object t) throws SerializationException {
|
|
|
+ if (t == null) {
|
|
|
+ return new byte[0];
|
|
|
+ } else {
|
|
|
+ try {
|
|
|
+ final byte[] bytes = this.objectMapper.writeValueAsBytes(t);
|
|
|
+ return Snappy.compress(bytes); //压缩
|
|
|
+ } catch (Exception var3) {
|
|
|
+ throw new SerializationException("Could not write JSON: " + var3.getMessage(), var3);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public void setObjectMapper(ObjectMapper objectMapper) {
|
|
|
+ Assert.notNull(objectMapper, "'objectMapper' must not be null");
|
|
|
+ this.objectMapper = objectMapper;
|
|
|
+ }
|
|
|
+
|
|
|
+ protected JavaType getJavaType(Class<?> clazz) {
|
|
|
+ return TypeFactory.defaultInstance().constructType(clazz);
|
|
|
+ }
|
|
|
+
|
|
|
+ static {
|
|
|
+ DEFAULT_CHARSET = StandardCharsets.UTF_8;
|
|
|
+ }
|
|
|
+}
|