forked from hazelcast/hazelcast-jet-code-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KafkaAvroSource.java
191 lines (169 loc) · 6.93 KB
/
KafkaAvroSource.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
/*
* 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 avro;
import com.hazelcast.jet.Jet;
import com.hazelcast.jet.JetInstance;
import com.hazelcast.jet.Job;
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 io.confluent.kafka.schemaregistry.rest.SchemaRegistryConfig;
import io.confluent.kafka.schemaregistry.rest.SchemaRegistryRestApplication;
import io.confluent.kafka.serializers.KafkaAvroDeserializer;
import io.confluent.kafka.serializers.KafkaAvroSerializer;
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.eclipse.jetty.server.Server;
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.SECONDS;
import static kafka.admin.AdminUtils.createTopic;
/**
* A sample which demonstrates how to consume items using Apache Avro
* serialization. An embedded schema registry server is used for Apache Avro
* schema registration.
*/
public class KafkaAvroSource {
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 EmbeddedZookeeper zkServer;
private ZkUtils zkUtils;
private KafkaServer kafkaServer;
private Server server;
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", KafkaAvroDeserializer.class.getName(),
"specific.avro.reader", "true",
"schema.registry.url", "http://localhost:8081",
"auto.offset.reset", AUTO_OFFSET_RESET), TOPIC))
.withoutTimestamps()
.drainTo(Sinks.logger());
return p;
}
public static void main(String[] args) throws Exception {
System.setProperty("hazelcast.logging.type", "log4j");
new KafkaAvroSource().go();
}
private void go() throws Exception {
try {
createKafkaCluster();
startSchemaRegistryServer();
createAndFillTopic();
JetInstance jet = Jet.newJetInstance();
Job job = jet.newJob(buildPipeline());
SECONDS.sleep(5);
cancel(job);
} finally {
server.stop();
Jet.shutdownAll();
shutdownKafkaCluster();
}
}
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", KafkaAvroSerializer.class.getName(),
"schema.registry.url", "http://localhost:8081");
try (KafkaProducer<Integer, User> 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, 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 startSchemaRegistryServer() throws Exception {
Properties props = props(
"listeners", "http://0.0.0.0:8081",
"kafkastore.connection.url", ZK_HOST + ':' + zkServer.port());
SchemaRegistryConfig config = new SchemaRegistryConfig(props);
SchemaRegistryRestApplication app = new SchemaRegistryRestApplication(config);
server = app.createServer();
server.start();
}
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;
}
}