Search code examples
springspring-rabbit

How to add more cached channels per cached connection in CacheMode.CONNECTION Spring AMQP


I'm using CachingConnectionFactory with CacheMode.CONNECTION and i see that only one channel is opened per connection. How can i add more channel per connection?

This is config code for ConnectionFactory and SimpleRabbitListenerContainerFactory

@Bean
public ConnectionFactory connectionFactory() {
    CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
    connectionFactory.setCacheMode(CachingConnectionFactory.CacheMode.CONNECTION);
    connectionFactory.setConnectionCacheSize(10);
    connectionFactory.setConnectionLimit(10);
    connectionFactory.setChannelCacheSize(500);
    connectionFactory.setChannelCheckoutTimeout(50);
    
    return connectionFactory;
}

@Bean("TEST_1_CONSUMER")
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(CachingConnectionFactory cachingConnectionFactory) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(cachingConnectionFactory);
    factory.setConcurrentConsumers(2);
    factory.setMaxConcurrentConsumers(5);

    return factory;
}

Solution

  • CachMode.CONNECTION will cache as many channels as you want on each connection, as long as you use the same connection.

    However, framework components, (listener containers, templates) will each use a different connection so, effectively, there is only one channel.

    If you obtain channels yourself, from a single connection, they will be cached.

    If you want framework components to share a pool of connections, you will need to create your own wrapper factory to manage that pool.