1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package io.hmit.common.redis.serializer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.IOUtils;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
/**
* Redis序列化
*
* @author zsh 408538940@qq.com
*/
public class JsonRedisSerializer<T> implements RedisSerializer<T> {
private static ParserConfig defaultRedisConfig = new ParserConfig();
static {
defaultRedisConfig.setAutoTypeSupport(true);
}
private Class<T> type;
public JsonRedisSerializer(Class<T> type) {
this.type = type;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(IOUtils.UTF8);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, IOUtils.UTF8);
return JSON.parseObject(str, type, defaultRedisConfig);
}
}