I'm fairly new to java message listeners and apache pulsar.
Assume that I've maintained a listener like so,
private MessageListener<byte[]> generateListener() {
MessageListener<byte[]> listener = (consumer, respMsg) -> {
String respM = new String(respMsg.getValue(), StandardCharsets.UTF_8);
logger.info(respM);
consumer.acknowledgeAsync(respMsg);
};
return listener;
}
And a Consumer instance like so,
Consumer<byte[]> c = consumerBuilder.messageListener(generateListener()).topic(topicName).subscriptionName("Consumer-" + i).subscribeAsync().get();
What I would like to know is how multiple incoming messages would be handled by this listener? Will each message be handled in a seperate thread as in the case of JMS listeners? If so, then how can I configure the number of threads to use - is it by using the ClientBuilder.listenerThreads() property?
Is there a need to maintain multiple listener objects respective to each consumer, when maintaining multiple consumers i.e, something like this -
consumerBuilder.clone().messageListener(generateListener()).topic(topicName).subscriptionName("Consumer-" + i).subscribeAsync() ?
The
ClientBuilder#listenerThreadsmethod allows configuring the size of an internal thread-pool that will be shared and used across allConsumersorReadersthat will be created from that client.Pulsar Client will give you the guarantee that a
MessageListenerfor a single consumer will always be invoked by the same thread, i.e that the providedMessageListenerdon't need to be thread-safe. So, YES it is prefered to use a dedicatedMessageListenerobject perConsumer.Note that this also ensure ordering.
So basically, if you only use a single
Consumerthen you can keep the listenerThreads to1(that is the default).Here is a complete example that can used to observe the behaviour :