forked from hazelcast/hazelcast-jet-code-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KafkaJsonSource.java
234 lines (201 loc) · 8.27 KB
/
KafkaJsonSource.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package json;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hazelcast.config.SerializerConfig;
import com.hazelcast.core.IMap;
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.Job;
import com.hazelcast.jet.config.JetConfig;
import com.hazelcast.jet.core.JobStatus;
import com.hazelcast.jet.kafka.KafkaSources;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.StreamSerializer;
import kafka.admin.RackAwareMode;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServer;
import kafka.utils.MockTime;
import kafka.utils.TestUtils;
import kafka.utils.ZKStringSerializer$;
import kafka.utils.ZkUtils;
import kafka.zk.EmbeddedZookeeper;
import org.I0Itec.zkclient.ZkClient;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.IntegerDeserializer;
import org.apache.kafka.common.serialization.IntegerSerializer;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.connect.json.JsonDeserializer;
import org.apache.kafka.connect.json.JsonSerializer;
import java.io.IOException;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.util.Properties;
import static com.hazelcast.jet.impl.util.Util.uncheckRun;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static kafka.admin.AdminUtils.createTopic;
/**
* A sample which demonstrates how to consume items using custom JSON
* serialization.
*/
public class KafkaJsonSource {
private static final String ZK_HOST = "127.0.0.1";
private static final String BROKER_HOST = "127.0.0.1";
private static final int SESSION_TIMEOUT = 30000;
private static final int CONNECTION_TIMEOUT = 30000;
private static final String AUTO_OFFSET_RESET = "earliest";
private static final String TOPIC = "topic";
private static final String SINK_MAP_NAME = "users";
private EmbeddedZookeeper zkServer;
private ZkUtils zkUtils;
private KafkaServer kafkaServer;
private int brokerPort;
private Pipeline buildPipeline() {
Pipeline p = Pipeline.create();
p.drawFrom(KafkaSources.kafka(props(
"bootstrap.servers", BROKER_HOST + ':' + brokerPort,
"group.id", "0",
"key.deserializer", IntegerDeserializer.class.getName(),
"value.deserializer", JsonDeserializer.class.getName(),
"auto.offset.reset", AUTO_OFFSET_RESET), TOPIC))
.withoutTimestamps()
.peek()
.drainTo(Sinks.map(SINK_MAP_NAME));
return p;
}
public static void main(String[] args) throws Exception {
System.setProperty("hazelcast.logging.type", "log4j");
new KafkaJsonSource().go();
}
private void go() throws Exception {
try {
createKafkaCluster();
createAndFillTopic();
JetConfig jetConfig = getJetConfigWithCustomSerialization();
JetInstance jet = Jet.newJetInstance(jetConfig);
Jet.newJetInstance(jetConfig);
long start = System.nanoTime();
Job job = jet.newJob(buildPipeline());
IMap<String, Integer> sinkMap = jet.getMap(SINK_MAP_NAME);
while (true) {
int mapSize = sinkMap.size();
System.out.format("Received %d entries in %d milliseconds.%n",
mapSize, NANOSECONDS.toMillis(System.nanoTime() - start));
if (mapSize == 20) {
SECONDS.sleep(1);
cancel(job);
break;
}
Thread.sleep(100);
}
} finally {
Jet.shutdownAll();
shutdownKafkaCluster();
}
}
private JetConfig getJetConfigWithCustomSerialization() {
JetConfig jetConfig = new JetConfig();
SerializerConfig serializerConfig = new SerializerConfig();
serializerConfig.setTypeClass(JsonNode.class);
serializerConfig.setImplementation(new StreamSerializer<JsonNode>() {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public int getTypeId() {
return 1;
}
@Override
public void destroy() {
}
@Override
public void write(ObjectDataOutput objectDataOutput, JsonNode jsonNode) throws IOException {
byte[] bytes = objectMapper.writeValueAsBytes(jsonNode);
objectDataOutput.write(bytes);
}
@Override
public JsonNode read(ObjectDataInput objectDataInput) throws IOException {
return objectMapper.readValue(objectDataInput.readByteArray(), JsonNode.class);
}
});
jetConfig.getHazelcastConfig().getSerializationConfig().addSerializerConfig(serializerConfig);
return jetConfig;
}
private void createAndFillTopic() {
createTopic(zkUtils, TOPIC, 4, 1, new Properties(), RackAwareMode.Disabled$.MODULE$);
Properties props = props(
"bootstrap.servers", BROKER_HOST + ':' + brokerPort,
"key.serializer", IntegerSerializer.class.getName(),
"value.serializer", JsonSerializer.class.getName());
ObjectMapper mapper = new ObjectMapper();
try (KafkaProducer<Integer, JsonNode> producer = new KafkaProducer<>(props)) {
for (int i = 0; i < 20; i++) {
User user = new User("name" + i, "pass" + i, i, i % 2 == 0);
producer.send(new ProducerRecord<>(TOPIC, i, mapper.valueToTree(user)));
}
}
}
private void createKafkaCluster() throws IOException {
System.setProperty("zookeeper.preAllocSize", Integer.toString(128));
zkServer = new EmbeddedZookeeper();
String zkConnect = ZK_HOST + ':' + zkServer.port();
ZkClient zkClient = new ZkClient(zkConnect, SESSION_TIMEOUT, CONNECTION_TIMEOUT, ZKStringSerializer$.MODULE$);
zkUtils = ZkUtils.apply(zkClient, false);
brokerPort = randomPort();
KafkaConfig config = new KafkaConfig(props(
"zookeeper.connect", zkConnect,
"broker.id", "0",
"log.dirs", Files.createTempDirectory("kafka-").toAbsolutePath().toString(),
"listeners", "PLAINTEXT://" + BROKER_HOST + ':' + brokerPort,
"offsets.topic.replication.factor", "1",
"offsets.topic.num.partitions", "1"));
Time mock = new MockTime();
kafkaServer = TestUtils.createServer(config, mock);
}
private void shutdownKafkaCluster() {
kafkaServer.shutdown();
zkUtils.close();
zkServer.shutdown();
}
private static void cancel(Job job) {
job.cancel();
while (job.getStatus() != JobStatus.FAILED) {
uncheckRun(() -> SECONDS.sleep(1));
}
}
private static int randomPort() throws IOException {
ServerSocket server = null;
try {
server = new ServerSocket(0);
return server.getLocalPort();
} finally {
if (server != null) {
server.close();
}
}
}
private static Properties props(String... kvs) {
final Properties props = new Properties();
for (int i = 0; i < kvs.length; ) {
props.setProperty(kvs[i++], kvs[i++]);
}
return props;
}
}