KevinBui
KevinBui

Reputation: 1139

Create RabbitTemplate without TracingMessagePostProcessor

I use Spring Cloud Sleuth integrated with Spring AMQP to enable traceId when publishing messages.

Sleuth automatically adds TracingMessagePostProcessor into RabbitTemplate.beforePublishPostProcessor to add trace headers to outgoing Rabbit messages.

I have a scenario: I have a batch of objects and want to publish them, like this:

List<Object> listObj = getData(...);
for (Object o : listObj) {
  rabbitTemplate.convertAndSend(exchange, routingKey, o);
}

When I consume messages, all messages have same traceId. I don't want this.

How can I create just a rabbitTemplate bean without TracingMessagePostProcessor? Or how to make every message I publish/consume have a different traceId?

I already have read the Spring Cloud Sleuth docs. I can use the config...

spring.sleuth.messaging.rabbit.enabled=false 

...to disable this feature, but I just want to disable it for a specified rabbitTemplate bean.

Upvotes: 1

Views: 575

Answers (2)

KevinBui
KevinBui

Reputation: 1139

I use RabbitTemplate.addBeforePublishPostProcessors to remove header b3 from message properties headers

@Autowired
public void removeTraceProcessor(RabbitTemplate noTraceRabbitTemplate) {
    noTraceRabbitTemplate.addBeforePublishPostProcessors(
        message -> {
            message.getMessageProperties().getHeaders().remove("b3");
            return message;
        }
    );
}

Second solution from @Artem-Bilan

@Bean
public RabbitTemplate noTraceRabbitTemplate(ConnectionFactory connFactoryLocal) {
    return new RabbitTemplate(connFactoryLocal) {
        @Override
        public void setBeforePublishPostProcessors(MessagePostProcessor... beforePublishPostProcessors) {
            super.setBeforePublishPostProcessors(
                Arrays.stream(beforePublishPostProcessors)
                .filter(p -> !p.getClass().getSimpleName().equals("TracingMessagePostProcessor"))
                .toArray(MessagePostProcessor[]::new)
            );
        }
    };
}

Upvotes: 0

Artem Bilan
Artem Bilan

Reputation: 121550

The logic in Open Zipkin Brave is like this:

 /** Instruments an existing {@linkplain RabbitTemplate} */
  public RabbitTemplate decorateRabbitTemplate(RabbitTemplate rabbitTemplate) {
    MessagePostProcessor[] beforePublishPostProcessors =
      appendTracingMessagePostProcessor(rabbitTemplate, beforePublishPostProcessorsField);
    if (beforePublishPostProcessors != null) {
      rabbitTemplate.setBeforePublishPostProcessors(beforePublishPostProcessors);
    }
    return rabbitTemplate;
  }

Since it is unconditional, I'd suggest you to override RabbitTemplate for that setBeforePublishPostProcessors() method and have its body empty or just remove that TracingMessagePostProcessor before propagating to super.

Upvotes: 1

Related Questions