MrShi
2025-08-19 ff087240b3dee29ce4e14ad0836e76b9fdf312cf
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
49
50
51
52
53
54
55
56
package com.doumee.config.cache;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.Nullable;
 
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
 
/**
 * Redis 值序列化器
 * @author  dm
 * @since 2025/03/31 16:44
 */
class RedisValueDefaultSerializer<T> implements RedisSerializer<T> {
 
    private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
 
    private final ParserConfig parserConfig = new ParserConfig();
 
    {
        parserConfig.setAutoTypeSupport(true);
    }
 
    private final Class<T> type;
 
    RedisValueDefaultSerializer(Class<T> type) {
        this.type = type;
    }
 
    public T deserialize(@Nullable byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        try {
            return JSON.parseObject(new String(bytes, DEFAULT_CHARSET), type, parserConfig);
        } catch (Exception e) {
            throw new SerializationException("Could not serialize value of redis: " + e.getMessage(), e);
        }
    }
 
    public byte[] serialize(@Nullable Object value) throws SerializationException {
        if (value == null) {
            return new byte[0];
        }
        try {
            return JSON.toJSONBytes(value, SerializerFeature.WriteClassName, SerializerFeature.PrettyFormat);
        } catch (Exception e) {
            throw new SerializationException("Could not serialize value of redis: " + e.getMessage(), e);
        }
    }
 
}