1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.caches.redis;
17
18 import com.esotericsoftware.kryo.kryo5.Kryo;
19 import com.esotericsoftware.kryo.kryo5.io.Input;
20 import com.esotericsoftware.kryo.kryo5.io.Output;
21
22 import java.util.Arrays;
23 import java.util.Set;
24 import java.util.concurrent.ConcurrentHashMap;
25
26
27
28
29
30
31 public enum KryoSerializer implements Serializer {
32
33 INSTANCE;
34
35
36
37
38 private ThreadLocal<Kryo> kryos = ThreadLocal.withInitial(Kryo::new);
39
40
41
42
43
44
45 private Set<Class<?>> unnormalClassSet;
46
47
48
49
50
51 private Set<Integer> unnormalBytesHashCodeSet;
52 private Serializer fallbackSerializer;
53
54 private KryoSerializer() {
55 unnormalClassSet = ConcurrentHashMap.newKeySet();
56 unnormalBytesHashCodeSet = ConcurrentHashMap.newKeySet();
57 fallbackSerializer = JDKSerializer.INSTANCE;
58 }
59
60 @Override
61 public byte[] serialize(Object object) {
62 if (unnormalClassSet.contains(object.getClass())) {
63
64 return fallbackSerializer.serialize(object);
65 }
66
67
68
69
70
71 try (Output output = new Output(200, -1)) {
72 kryos.get().writeClassAndObject(output, object);
73 return output.toBytes();
74 } catch (Exception e) {
75
76 unnormalClassSet.add(object.getClass());
77 return fallbackSerializer.serialize(object);
78 }
79 }
80
81 @Override
82 public Object unserialize(byte[] bytes) {
83 if (bytes == null) {
84 return null;
85 }
86 int hashCode = Arrays.hashCode(bytes);
87 if (unnormalBytesHashCodeSet.contains(hashCode)) {
88
89 return fallbackSerializer.unserialize(bytes);
90 }
91
92
93
94
95
96 try (Input input = new Input()) {
97 input.setBuffer(bytes);
98 return kryos.get().readClassAndObject(input);
99 } catch (Exception e) {
100
101 unnormalBytesHashCodeSet.add(hashCode);
102 return fallbackSerializer.unserialize(bytes);
103 }
104 }
105
106 }