forked from sijie/pulsar-avro-schema-example
/
TweetProducer.java
51 lines (44 loc) · 1.94 KB
/
TweetProducer.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
package org.apache.pulsar.examples;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.impl.schema.AvroSchema;
/**
* Producer to produce tweets in Avro format.
*/
public class TweetProducer {
public static void main(String[] args) {
if (args.length < 1) {
System.err.println("Usage: TweetProducer [service-url]");
return;
}
String serviceUrl = args[0];
try (PulsarClient client = PulsarClient.builder()
.serviceUrl(serviceUrl)
.build()) {
try (Producer<TwitterSchema> producer = client.newProducer(AvroSchema.of(TwitterSchema.class))
.topic("twitter-avro")
.create()) {
for (int i = 0; i < 10; i++) {
Fixed fixed = new Fixed("Hello".getBytes(StandardCharsets.UTF_8));
TwitterSchema tweet = new TwitterSchema("user-" + i, "tweet-" + i, fixed, System.currentTimeMillis());
DatumWriter<TwitterSchema> writer = new SpecificDatumWriter<>(TwitterSchema.class);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Encoder encoder = EncoderFactory.get().jsonEncoder(TwitterSchema.getClassSchema(), bos, true);
writer.write(tweet, encoder);
encoder.flush();
System.out.println("Tweet JSON: " + bos.toString("UTF-8"));
producer.send(tweet);
}
System.out.println("Successfully produce 10 tweets");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}