How can I pool channels in rabbitmq?

前端 未结 2 689
猫巷女王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 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.

提交回复
热议问题