-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
KryoTupleSerializer.java
83 lines (72 loc) · 2.76 KB
/
KryoTupleSerializer.java
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
package backtype.storm.serialization;
import backtype.storm.task.TopologyContext;
import backtype.storm.tuple.Tuple;
import backtype.storm.utils.CRC32OutputStream;
import backtype.storm.utils.ThreadResourceManager;
import backtype.storm.utils.WritableUtils;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Map;
public class KryoTupleSerializer implements ITupleSerializer {
ThreadResourceManager<Worker> _manager;
public KryoTupleSerializer(final Map conf, final TopologyContext context) {
_manager = new ThreadResourceManager<Worker>(new ThreadResourceManager.ResourceFactory<Worker>() {
@Override
public Worker makeResource() {
return new Worker(conf, context);
}
});
}
@Override
public byte[] serialize(Tuple tuple) {
Worker worker = _manager.acquire();
try {
return worker.serialize(tuple);
} finally {
_manager.release(worker);
}
}
@Override
public long crc32(Tuple tuple) {
Worker worker = _manager.acquire();
try {
return worker.crc32(tuple);
} finally {
_manager.release(worker);
}
}
private static class Worker implements ITupleSerializer {
ByteArrayOutputStream _outputter;
DataOutputStream _dataOutputter;
KryoValuesSerializer _kryo;
SerializationFactory.IdDictionary _ids;
public Worker(Map conf, TopologyContext context) {
_outputter = new ByteArrayOutputStream();
_dataOutputter = new DataOutputStream(_outputter);
_kryo = new KryoValuesSerializer(conf);
_ids = new SerializationFactory.IdDictionary(context.getRawTopology());
}
public byte[] serialize(Tuple tuple) {
try {
_outputter.reset();
WritableUtils.writeVInt(_dataOutputter, tuple.getSourceTask());
WritableUtils.writeVInt(_dataOutputter, _ids.getStreamId(tuple.getSourceComponent(), tuple.getSourceStreamId()));
tuple.getMessageId().serialize(_dataOutputter);
_kryo.serializeInto(tuple.getValues(), _outputter);
return _outputter.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public long crc32(Tuple tuple) {
try {
CRC32OutputStream hasher = new CRC32OutputStream();
_kryo.serializeInto(tuple.getValues(), hasher);
return hasher.getValue();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}