-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMyConsumer.java
58 lines (50 loc) · 1.73 KB
/
MyConsumer.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
import java.util.concurrent.TimeUnit;
import org.apache.pulsar.client.api.ConsumerBuilder;
import org.apache.pulsar.client.api.MessageListener;
import org.apache.pulsar.client.api.PulsarClient;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.client.api.SubscriptionType;
public class MyConsumer {
private static final int NUM_CONSUMERS = 20;
public static void main(String[] args) throws PulsarClientException {
if (args.length != 2) {
System.err.println("MyConsumer topic subscription ");
}
String topic = args[0];
String subscriptionName = args[1];
System.err.println(topic + " " + subscriptionName);
PulsarClient client =
PulsarClient.builder()
.serviceUrl("pulsar://localhost:6650")
.listenerThreads(NUM_CONSUMERS)
.build();
MessageListener<byte[]> listener =
(consumer, msg) -> {
synchronizedPrint(
consumer.getConsumerName() + " " + msg.getKey() + " " + new String(msg.getValue()));
consumer.acknowledgeAsync(msg);
};
ConsumerBuilder<byte[]> builder =
client
.newConsumer()
.topic(topic)
.subscriptionName(subscriptionName)
.subscriptionType(SubscriptionType.Key_Shared)
.messageListener(listener)
.negativeAckRedeliveryDelay(1, TimeUnit.SECONDS);
for (int i = 0; i < NUM_CONSUMERS; ++i) {
builder.subscribe();
}
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
e.printStackTrace();
}
}
}
private static synchronized void synchronizedPrint(String str) {
System.out.println(str);
}
}