2

In question How to set the consumer-tag value in spring-amqp it is being asked how to change the consumer tag when using Spring Amqp and the answer suggests to provide an implementation of ConsumerTagStrategy.

I'm using Spring Boot 2.0.5 and I'm trying to figure out if I can do the same customization, though I can't find any configuration property about that nor providing a bean of type ConsumerTagStrategy seems to work.

How should I go about this?

watery
  • 5,026
  • 9
  • 52
  • 92

3 Answers3

6

Override boot's container factory bean declaration and add it there.

@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
        SimpleRabbitListenerContainerFactoryConfigurer configurer,
        ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    configurer.configure(factory, connectionFactory);
    factory.setConsumerTagStrategy(q -> "myConsumerFor." + q);
    return factory;
}

Tag

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
0

Even Gary's answer is very good it is not working always. For example in Spring Boot with autoconfiguration and using RabbitListener you probably end with some weird situation where application refuse to start or your factory will not be used. I would recommend to used BeanPostProcessor instead. There is a simple example following:

@Component
public class ConsumerTagByAppSetter implements BeanPostProcessor {

    private final String appName;

    public ConsumerTagByAppSetter(@Value("${spring.application.name}") String appName) {
        this.appName = appName;
    }

    @Override
    public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        if (bean instanceof SimpleRabbitListenerContainerFactory) {
            ((SimpleRabbitListenerContainerFactory) bean).setConsumerTagStrategy(q -> appName + "." + q);
        }
        return bean;
    }
}

This post processor is applied to the factory created and customized by auto configuration and changes just the way how consumer tag is generated which I consider much safer and out of the box than trying to start from scratch...

Majlanky
  • 198
  • 2
  • 9
0

You do not have to override SimpleRabbitListenerContainerFactory.

It is enough to customize it by creating the extra bean which will be applied by spring boot autoconfiguration.

    @Bean
    ContainerCustomizer<SimpleMessageListenerContainer> containerCustomizer(@Value("${spring.application.name}") String applicationName) {
        return container -> container.setConsumerTagStrategy(queue -> applicationName + "_" + UUID.randomUUID());
    }
KrzysztofS
  • 66
  • 2