Best practice for receiving messages

Hello,

I was going over documentation of HiveMQ Client, and the given github examples, but I am still uncertain about one thing.

What is the best practice for receiving messages on topics that a client is subscribed to? Should there be a thread that receives messages and then spawns other threads to deal with them based on topics? Most of the examples show receiving one message and ending there, but that is obviously not a realistic scenario. Should a receiving thread just be in an endless loop, or are there better ways to deal with regularly incoming messages, and am I missing something here?

Thanks in advance.

Hello @freeze

Welcome to the HiveMQ community forum.

Do you want to process the message once it’s received by the subscriber? Can you please elaborate more on your question?

Kind regards,
Sheetal

Hi @SShet
Thanks for the quick response.

Basically, I want to make a client that subscribes to certain topics(which I understood how to do), and then I want to process the published messages. There is a given example in the tutorials that looks something similar to this:

        try (final Mqtt5BlockingClient.Mqtt5Publishes publishes = client.publishes(MqttGlobalPublishFilter.ALL)) {

            client.subscribeWith().topicFilter("test/topic").qos(MqttQos.AT_LEAST_ONCE).send();

            Optional<Mqtt5Publish> message = publishes.receive(10, TimeUnit.SECONDS);
}

Now, I’d like to know what is the best place for a code that receives the message? As we generally don’t know when the message will be received, I assume that there should be a separate thread that deals with incoming messages, so that the rest of the client isn’t blocked, as it may peform different actions in the mean time. Also, I want to keep receiving published messages, so I also assume that this piece of code should be placed in a loop of some sort.

Is there a different way to know when a message has been published on a certain topic? Also, would it be a good idea to receive published messages of different topics in different threads, or is it usually better to have one thread constantly check for any published messages that we are subscribed to, and then forward the tasks that may need to be done to new threads once it checks the topic and the payload of the message?

I might be failing to fundamentally understand something here, so I hope that my questions somewhat make sense.

Hi Freeze,

Thanks for the question. In order to process messages without the rest of the client being blocked,
the best practice here is to use a different API flavor. Both Async and Reactive should work.

I hope this will help you with your project

Kind regards,
Dasha from HiveMQ support