forked from hazelcast/hazelcast-jet-code-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KafkaSource.java
170 lines (149 loc) · 6.46 KB
/
KafkaSource.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
/*
* Copyright (c) 2008-2018, 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.
*/
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.Job;
import com.hazelcast.jet.kafka.KafkaSources;
import com.hazelcast.jet.config.InstanceConfig;
import com.hazelcast.jet.config.JetConfig;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.IMapJet;
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.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Time;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Properties;
import static java.lang.Runtime.getRuntime;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static kafka.admin.AdminUtils.createTopic;
/**
* A sample which consumes two Kafka topics and writes
* the received items to an {@code IMap}.
**/
public class KafkaSource {
private static final int MESSAGE_COUNT_PER_TOPIC = 1_000_000;
private static final String BOOTSTRAP_SERVERS = "localhost:9092";
private static final String AUTO_OFFSET_RESET = "earliest";
private static final String SINK_NAME = "sink";
private EmbeddedZookeeper zkServer;
private ZkUtils zkUtils;
private KafkaServer kafkaServer;
public static void main(String[] args) throws Exception {
System.setProperty("hazelcast.logging.type", "log4j");
new KafkaSource().run();
}
private Pipeline buildPipeline() {
Pipeline p = Pipeline.create();
p.drawFrom(KafkaSources.kafka(brokerProperties(), "t1", "t2"))
.drainTo(Sinks.map(SINK_NAME));
return p;
}
private void run() throws Exception {
JetConfig cfg = new JetConfig();
cfg.setInstanceConfig(new InstanceConfig().setCooperativeThreadCount(
Math.max(1, getRuntime().availableProcessors() / 2)));
try {
createKafkaCluster();
fillTopics();
JetInstance instance = Jet.newJetInstance(cfg);
Jet.newJetInstance(cfg);
IMapJet<String, Integer> sinkMap = instance.getMap(SINK_NAME);
Pipeline p = buildPipeline();
long start = System.nanoTime();
Job job = instance.newJob(p);
while (true) {
int mapSize = sinkMap.size();
System.out.format("Received %d entries in %d milliseconds.%n",
mapSize, NANOSECONDS.toMillis(System.nanoTime() - start));
if (mapSize == MESSAGE_COUNT_PER_TOPIC * 2) {
job.cancel();
break;
}
Thread.sleep(100);
}
} finally {
Jet.shutdownAll();
shutdownKafkaCluster();
}
}
// Creates an embedded zookeeper server and a kafka broker
private void createKafkaCluster() throws IOException {
zkServer = new EmbeddedZookeeper();
String zkConnect = "localhost:" + zkServer.port();
ZkClient zkClient = new ZkClient(zkConnect, 30000, 30000, ZKStringSerializer$.MODULE$);
zkUtils = ZkUtils.apply(zkClient, false);
KafkaConfig config = new KafkaConfig(props(
"zookeeper.connect", zkConnect,
"broker.id", "0",
"log.dirs", Files.createTempDirectory("kafka-").toAbsolutePath().toString(),
"offsets.topic.replication.factor", "1",
"listeners", "PLAINTEXT://localhost:9092"));
Time mock = new MockTime();
kafkaServer = TestUtils.createServer(config, mock);
}
// Creates 2 topics (t1, t2) with different partition counts (32, 64) and fills them with items
private void fillTopics() {
createTopic(zkUtils, "t1", 32, 1, new Properties(), RackAwareMode.Disabled$.MODULE$);
createTopic(zkUtils, "t2", 64, 1, new Properties(), RackAwareMode.Disabled$.MODULE$);
System.out.println("Filling Topics");
Properties props = props(
"bootstrap.servers", "localhost:9092",
"key.serializer", StringSerializer.class.getName(),
"value.serializer", IntegerSerializer.class.getName());
try (KafkaProducer<String, Integer> producer = new KafkaProducer<>(props)) {
for (int i = 1; i <= MESSAGE_COUNT_PER_TOPIC; i++) {
producer.send(new ProducerRecord<>("t1", "t1-" + i, i));
producer.send(new ProducerRecord<>("t2", "t2-" + i, i));
}
System.out.println("Published " + MESSAGE_COUNT_PER_TOPIC + " messages to topic t1");
System.out.println("Published " + MESSAGE_COUNT_PER_TOPIC + " messages to topic t2");
}
}
private void shutdownKafkaCluster() {
kafkaServer.shutdown();
zkUtils.close();
zkServer.shutdown();
}
private static Properties brokerProperties() {
return props(
"bootstrap.servers", BOOTSTRAP_SERVERS,
"key.deserializer", StringDeserializer.class.getCanonicalName(),
"value.deserializer", IntegerDeserializer.class.getCanonicalName(),
"auto.offset.reset", AUTO_OFFSET_RESET);
}
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;
}
}