测试用户
2023-04-13 43393f2bb11cbf9e6af40077bbc5284660e8a754
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.common.redis.serializer;
 
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
 
import java.io.ByteArrayOutputStream;
 
/**
 * @author xiaobzhou
 * date 2019-07-10 19:00
 */
public class KryoRedisSerializer<T> implements RedisSerializer<T> {
 
    private static final Logger LOG = LoggerFactory.getLogger(KryoRedisSerializer.class);
 
    public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
 
    /**
     * 初始化KRYO对象
     */
    private static final ThreadLocal<Kryo> KRYO = ThreadLocal.withInitial(Kryo::new);
 
    private Class<T> classType;
 
    public void cleanKryo() {
        KRYO.remove();
    }
    public KryoRedisSerializer(Class<T> classType) {
        super();
        this.classType = classType;
    }
 
    /**
     * Kryo序列化方法
     *
     * @param o
     * @return
     * @throws SerializationException
     */
    @Override
    public byte[] serialize(T o) throws SerializationException {
 
        if (o == null) {
            return EMPTY_BYTE_ARRAY;
        }
 
        Kryo kryo = KRYO.get();
        kryo.setReferences(false);
        kryo.register(classType);
 
        try {
            ByteArrayOutputStream byteOps = new ByteArrayOutputStream();
            Output output = new Output(byteOps);
            kryo.writeClassAndObject(output, o);
            output.flush();
            return byteOps.toByteArray();
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
        }
 
        return EMPTY_BYTE_ARRAY;
    }
 
    /**
     * Kryo反序列化方法
     *
     * @param bytes
     * @return
     * @throws SerializationException
     */
    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
 
        if (bytes != null) {
            Kryo kryo = KRYO.get();
            kryo.setReferences(false);
            kryo.register(classType);
 
            try {
                Input input = new Input(bytes);
                return (T) kryo.readClassAndObject(input);
            } catch (Exception ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
 
        return null;
    }
}