forked from hazelcast/hazelcast-jet-code-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KafkaSink.java
179 lines (156 loc) · 6.45 KB
/
KafkaSink.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
/*
* 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.
*/
import com.hazelcast.jet.IMapJet;
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.Job;
import com.hazelcast.jet.config.InstanceConfig;
import com.hazelcast.jet.config.JetConfig;
import com.hazelcast.jet.kafka.KafkaSinks;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sources;
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.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.security.auth.SecurityProtocol;
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 scala.Option;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.Properties;
import static java.lang.Runtime.getRuntime;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
/**
* A sample which consumes an {@code IMap} and writes
* the received items to a Kafka Topic.
**/
public class KafkaSink {
private static final int MESSAGE_COUNT = 50_000;
private static final String BOOTSTRAP_SERVERS = "localhost:9092";
private static final String AUTO_OFFSET_RESET = "earliest";
private static final String SOURCE_NAME = "source";
private static final String SINK_TOPIC_NAME = "t1";
private EmbeddedZookeeper zkServer;
private ZkUtils zkUtils;
private KafkaServer kafkaServer;
private KafkaConsumer kafkaConsumer;
private static Pipeline buildPipeline() {
Pipeline p = Pipeline.create();
p.drawFrom(Sources.map(SOURCE_NAME))
.drainTo(KafkaSinks.kafka(props(
"bootstrap.servers", BOOTSTRAP_SERVERS,
"key.serializer", StringSerializer.class.getCanonicalName(),
"value.serializer", IntegerSerializer.class.getCanonicalName()),
SINK_TOPIC_NAME));
return p;
}
public static void main(String[] args) throws Exception {
System.setProperty("hazelcast.logging.type", "log4j");
new KafkaSink().run();
}
private void run() throws Exception {
JetConfig cfg = new JetConfig();
cfg.setInstanceConfig(new InstanceConfig().setCooperativeThreadCount(
Math.max(1, getRuntime().availableProcessors() / 2)));
try {
createKafkaCluster();
JetInstance instance = Jet.newJetInstance(cfg);
Jet.newJetInstance(cfg);
IMapJet<String, Integer> sourceMap = instance.getMap(SOURCE_NAME);
fillIMap(sourceMap);
Pipeline p = buildPipeline();
long start = System.nanoTime();
Job job = instance.newJob(p);
System.out.println("Consuming Topics");
kafkaConsumer = TestUtils.createConsumer(
BOOTSTRAP_SERVERS,
"verification-consumer",
AUTO_OFFSET_RESET,
true,
true,
4096,
SecurityProtocol.PLAINTEXT,
Option.<File>empty(),
Option.<Properties>empty(),
new StringDeserializer(),
new IntegerDeserializer());
kafkaConsumer.subscribe(Collections.singleton(SINK_TOPIC_NAME));
int totalMessagesSeen = 0;
while (true) {
ConsumerRecords records = kafkaConsumer.poll(10000);
totalMessagesSeen += records.count();
System.out.format("Received %d entries in %d milliseconds.%n",
totalMessagesSeen, NANOSECONDS.toMillis(System.nanoTime() - start));
if (totalMessagesSeen == MESSAGE_COUNT) {
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);
}
private void fillIMap(IMapJet<String, Integer> sourceMap) {
System.out.println("Filling IMap");
for (int i = 1; i <= MESSAGE_COUNT; i++) {
sourceMap.put("t1-" + i, i);
}
System.out.println("Published " + MESSAGE_COUNT + " messages to IMap -> " + SOURCE_NAME);
}
private void shutdownKafkaCluster() {
kafkaServer.shutdown();
kafkaConsumer.close();
zkUtils.close();
zkServer.shutdown();
}
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;
}
}