提交 | 用户 | 时间
|
e57a89
|
1 |
package com.jcdm.framework.config; |
懒 |
2 |
|
|
3 |
import java.nio.charset.Charset; |
|
4 |
import org.springframework.data.redis.serializer.RedisSerializer; |
|
5 |
import org.springframework.data.redis.serializer.SerializationException; |
|
6 |
import com.alibaba.fastjson2.JSON; |
|
7 |
import com.alibaba.fastjson2.JSONReader; |
|
8 |
import com.alibaba.fastjson2.JSONWriter; |
|
9 |
import com.alibaba.fastjson2.filter.Filter; |
|
10 |
import com.jcdm.common.constant.Constants; |
|
11 |
|
|
12 |
/** |
|
13 |
* Redis使用FastJson序列化 |
|
14 |
* |
|
15 |
* @author jc |
|
16 |
*/ |
|
17 |
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> |
|
18 |
{ |
|
19 |
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); |
|
20 |
|
|
21 |
static final Filter AUTO_TYPE_FILTER = JSONReader.autoTypeFilter(Constants.JSON_WHITELIST_STR); |
|
22 |
|
|
23 |
private Class<T> clazz; |
|
24 |
|
|
25 |
public FastJson2JsonRedisSerializer(Class<T> clazz) |
|
26 |
{ |
|
27 |
super(); |
|
28 |
this.clazz = clazz; |
|
29 |
} |
|
30 |
|
|
31 |
@Override |
|
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, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET); |
|
39 |
} |
|
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 |
|
|
50 |
return JSON.parseObject(str, clazz, AUTO_TYPE_FILTER); |
|
51 |
} |
|
52 |
} |