This commit is contained in:
@@ -1,10 +1,12 @@
|
||||
package com.imyeyu.spring.util;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.data.redis.serializer.RedisSerializer;
|
||||
import org.springframework.data.redis.serializer.SerializationException;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
@@ -83,20 +85,24 @@ public class RedisSerializers {
|
||||
};
|
||||
|
||||
/**
|
||||
* Gson 序列化
|
||||
* Json 序列化
|
||||
*
|
||||
* @param <T> 数据类型
|
||||
* @param clazz 数据类型
|
||||
* @return Redis 序列化器
|
||||
*/
|
||||
public static <T> RedisSerializer<T> gsonSerializer(Class<T> clazz) {
|
||||
public static <T> RedisSerializer<T> jacksonSerializer(Class<T> clazz) {
|
||||
return new RedisSerializer<>() {
|
||||
|
||||
private static final Gson GSON = new Gson();
|
||||
private static final ObjectMapper JACKSON = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public byte[] serialize(T object) throws SerializationException {
|
||||
return GSON.toJson(object).getBytes(StandardCharsets.UTF_8);
|
||||
try {
|
||||
return JACKSON.writeValueAsString(object).getBytes(StandardCharsets.UTF_8);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -104,7 +110,11 @@ public class RedisSerializers {
|
||||
if (bytes == null) {
|
||||
return null;
|
||||
}
|
||||
return GSON.fromJson(new String(bytes, StandardCharsets.UTF_8), clazz);
|
||||
try {
|
||||
return JACKSON.readValue(new String(bytes, StandardCharsets.UTF_8), clazz);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user