Fredrik Rambris
Fredrik Rambris

Reputation: 356

Open and close Channel with each publish in RabbitMQ Java Client

Scenario

I'm writing a Java application that imports products to a database from several different sources and then export the updated products to other systems like search engines and RSS feeds. Multiple imports, multiple exports. As its crucial that some of the exporters gets the updates ASAP I'm letting them stay running and listen for updates via queues in a RabbitMQ instance. Some importers will process files in bulk (meaning there will be many updates in close proximity), some importers with get updates sporadically (a few updates an hour, like from an admin). Each importer will have an instance of UpdateNotifier.

Example

This is the (somewhat simplified) class for adding IDs of the updated products to the RabbitMQ exchange:

public class UpdateNotifier
{
    private Connection conn;

    public UpdateNotifier(Connection alreadyOpenConnection)
    {
        conn = alreadyOpenConnection;
    }

    public void productIsUpdated(String id)
    {
        Channel chan = conn.createChannel();

        publishTheMessageToExchange(chan, id);

        chan.close();
    }
}

Question

Is it advisable to open a new channel for each publish and then closing it or would it be better to cache the Channel within each instance of the UpdateNotifier?

Maybe two different notifiers, one for bulk updates that keep a channel in the instance and one for sporadic updates that open and close the channel with each update?

So it boils down to: How costly is it to open and close Channels?

Upvotes: 2

Views: 2194

Answers (1)

Gabriele Santomaggio
Gabriele Santomaggio

Reputation: 22682

Create and destroy a channels it is a very easy and fast operation for RabbitMQ.

But, if you need an high throughput create/destroy a channel for each publish can impact the performance.

For my point of view, you don't need to cache channels etc, just use one channel for thread and you are safe.

I'd suggest to read this https://www.rabbitmq.com/production-checklist.html and https://www.rabbitmq.com/networking.html .

The links can help you to tune RabbitMQ

Upvotes: 6

Related Questions