How can I combine channels in rabbitmq?

I tried to exchange communication between streams and opened channels only when creating streams, but after learning a little more, I think I want to try connection pooling as well. How can I do this on rabbitmq? or is it a general idea that I can apply as a whole? My goal is to spawn X threads, and then they don't need to open new channels (which requires a round-robin deployment between the client and server).

Since threads are their own class, I'm not sure if I need to put the pool in the class itself that spawns the threads, or where do they go? I also have several types of threads that I would like to share with these connections between (not just one). Is it possible?

Just to give you a general idea of ​​how connections / channels are involved in rabbitmq:

 ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); //I want to share several of these between threads 
+7
source share
2 answers

All you need is a pool of Channel objects from which your streams can be retrieved.

Apache Sharing already has a shared ObjectPool that you can use.

The javadoc for the interface can be found here: http://commons.apache.org/pool/api-1.6/org/apache/commons/pool/ObjectPool.html

javadoc for one of its pre-built implementations can be found here: http://commons.apache.org/pool/api-1.6/org/apache/commons/pool/impl/GenericObjectPool.html

A tutorial on its use can be found here: http://commons.apache.org/pool/examples.html

If this is too complicated for you, you just need to write a class that manages the set of Channel objects, allowing the threads to check them and return them to the pool with the appropriate synchronization to prevent two threads from getting the same Channel

+6
source

You can also use the ThreadLocal object if you use channels.

RabbitMq advises you to use channels in the stream so that it is perfect.

Code example:

  private final ThreadLocal<Channel> channels = new ThreadLocal<>(); ... Channel channel = channels.get(); if (channel == null){ channel = connection.createChannel(); channels.set(channel); } 

there is no need to close the channels, as they will be closed by your application when the connection is closed. Although this solution may not suit you if you strongly create new threads, as you allocate many new channels that will never be closed. But if you do something like this, you are probably mistaken.

+3
source

All Articles