0
votes

My app has multiple threads that publish messages to a single RabbitMQ cluster.
Reading the rabbit docs: i read the following:

For applications that use multiple threads/processes for processing, it is very common to open a new channel per thread/process and not share channels between them.

And I understand that instead of opening multiple connection (expensive)
it is better to open multiple channels.

But why not use a single channel to all threads?
What are the benefits of using multiple channels over a single channel?

1
That shared channel would be a shared resource and require that you ensure only one thread at a time use that resources--which could drastically impact the performance of multi-threading (if not make it completely moot). - Peter Ritchie

1 Answers

3
votes

AMQP has the concept of Channel to provide more flexibility over reliable TCP connections. Opening a TCP connection per message would be extremely expensive, so they came up with the idea of logical Channels within a connection.

It is not a good idea to use a Channel for all the threads because if anything fails in a particular thread and the Channel dies, the rest of the threads will throw the exception AlreadyClosedException. A channel can die for multiple reasons: for example for trying to declare something that is already declared with other parameters or trying to cancel a consumer which doesn't exist, publishing to an exchange that doesn't exist, etc...

My best advice would be to have an object that holds a Channel in a local variable and also implements ShutdownListener interface, so every time the channel fails, it is able to recover and create a new one from a connection. So I would say that the main benefit is failure tolerance and scalability, since if a Channel dies it won't affect the rest.