|
| 1 | +package com.baeldung; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +import org.apache.pulsar.client.api.Consumer; |
| 6 | +import org.apache.pulsar.client.api.Message; |
| 7 | +import org.apache.pulsar.client.api.PulsarClient; |
| 8 | +import org.apache.pulsar.client.api.SubscriptionType; |
| 9 | + |
| 10 | +public class ConsumerTest { |
| 11 | + |
| 12 | + private static final String SERVICE_URL = "pulsar://localhost:6650"; |
| 13 | + private static final String TOPIC_NAME = "test-topic"; |
| 14 | + private static final String SUBSCRIPTION_NAME = "test-subscription"; |
| 15 | + |
| 16 | + public static void main(String[] args) throws IOException { |
| 17 | + // Create a Pulsar client instance. A single instance can be shared across many |
| 18 | + // producers and consumer within the same application |
| 19 | + PulsarClient client = PulsarClient.builder() |
| 20 | + .serviceUrl(SERVICE_URL) |
| 21 | + .build(); |
| 22 | + |
| 23 | + //Configure consumer specific settings. |
| 24 | + Consumer<byte[]> consumer = client.newConsumer() |
| 25 | + .topic(TOPIC_NAME) |
| 26 | + // Allow multiple consumers to attach to the same subscription |
| 27 | + // and get messages dispatched as a queue |
| 28 | + .subscriptionType(SubscriptionType.Shared) |
| 29 | + .subscriptionName(SUBSCRIPTION_NAME) |
| 30 | + .subscribe(); |
| 31 | + |
| 32 | + |
| 33 | + // Once the consumer is created, it can be used for the entire application lifecycle |
| 34 | + System.out.println("Created consumer for the topic "+ TOPIC_NAME); |
| 35 | + |
| 36 | + do { |
| 37 | + // Wait until a message is available |
| 38 | + Message<byte[]> msg = consumer.receive(); |
| 39 | + |
| 40 | + // Extract the message as a printable string and then log |
| 41 | + String content = new String(msg.getData()); |
| 42 | + System.out.println("Received message '"+content+"' with ID "+msg.getMessageId()); |
| 43 | + |
| 44 | + // Acknowledge processing of the message so that it can be deleted |
| 45 | + consumer.acknowledge(msg); |
| 46 | + } while (true); |
| 47 | + } |
| 48 | +} |
0 commit comments