yangys
2024-10-25 9faa74e1912022dc6e54c3e93426946876b5d83a
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
package com.qianwen.mdc.collect.config.redis;
 
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import org.springframework.cache.interceptor.SimpleKey;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.data.redis.serializer.RedisSerializer;
 
public class RedisKeySerializer implements RedisSerializer<Object> {
    private final Charset charset;
    private final ConversionService converter;
 
    public RedisKeySerializer() {
        this(StandardCharsets.UTF_8);
    }
 
    public RedisKeySerializer(Charset charset) {
        Objects.requireNonNull(charset, "Charset must not be null");
        this.charset = charset;
        this.converter = DefaultConversionService.getSharedInstance();
    }
 
    public Object deserialize(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        return new String(bytes, this.charset);
    }
 
    public byte[] serialize(Object object) {
        String key;
        Objects.requireNonNull(object, "redis key is null");
        if (object instanceof SimpleKey) {
            key = "";
        } else if (object instanceof String) {
            key = (String) object;
        } else {
            key = this.converter.convert(object, String.class);
        }
        return key.getBytes(this.charset);
    }
}