How can I pool channels in rabbitmq?

前端 未结 2 729
猫巷女王i
猫巷女王i 2021-02-20 05:24

I have been trying to share connection between threads and have channels open only on thread creation but after researching a bit more, I think I want to also try to conne

相关标签:
2条回答
  • 2021-02-20 06:14

    You can also use ThreadLocal object, in case you use the channels.

    RabbitMQ advises you to use channels per thread, so that would be a perfect match.

    Sample code:

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

    no need to close the channels, as they will be closed by your application when the connection is closed.

    However, this solution might not suit you well if you're heavily creating new threads since that will allocate a lot of new channels that will never be closed. But if you do something like that, you are probably doing something wrong.

    0 讨论(0)
  • 2021-02-20 06:28

    All you need is a pool of Channel objects that your threads can pull from.

    The Apache commons actually already has a generic ObjectPool 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

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

    A tutorial for using it can be found here: http://commons.apache.org/pool/examples.html

    If this is over-complicated for you simple needs, really all you need to do is write a class that manages a set of Channel objects, allowing threads to check them out and return them to the pool, with the appropriate synchronization to prevent two threads from getting ahold of the same Channel

    0 讨论(0)
提交回复
热议问题