Search code examples
spring-cloud-configspring-rabbit

Use Spring Cloud Spring Service Connector with RabbitMQ and start publisher config function


I connect RabbitMQ with sprin cloud config:

@Bean
public ConnectionFactory rabbitConnectionFactory() {
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put("publisherConfirms", true);
    RabbitConnectionFactoryConfig rabbitConfig = new RabbitConnectionFactoryConfig(properties);
    return connectionFactory().rabbitConnectionFactory(rabbitConfig);
}

2.Set rabbitTemplate.setMandatory(true) and setConfirmCallback():

@Bean
public RabbitTemplate rabbitTemplate() {
   RabbitTemplate template = new RabbitTemplate(connectionFactory);
   template.setMandatory(true);
   template.setMessageConverter(new Jackson2JsonMessageConverter());
   template.setConfirmCallback((correlationData, ack, cause) -> {
      if (!ack) {
          System.out.println("send message failed: " + cause + correlationData.toString());
      } else {
          System.out.println("Publisher Confirm" + correlationData.toString());
      }
  });
  return template;
}

3.Send message to queue to invoke the publisherConfirm and print log.

@Component
public class TestSender {

@Autowired
private RabbitTemplate rabbitTemplate;

@Scheduled(cron = "0/5 * *  * * ? ")
public void send() {
    this.rabbitTemplate.convertAndSend(EXCHANGE, "routingkey", "hello world",
        (Message m) -> {
            m.getMessageProperties().setHeader("tenant", "aaaaa");
            return m;
        }, new CorrelationData(UUID.randomUUID().toString()));
    Date date = new Date();
    System.out.println("Sender Msg Successfully - " + date);
 }
}

But publisherConfirm have not worked.The log have not been printed. Howerver true or false, log shouldn't been absent.


Solution

  • Mandatory is not needed for confirms, only returns.

    Some things to try:

    1. Turn on DEBUG logging to see it it helps; there are some logs generated regarding confirms.
    2. Add some code

    .

    template.execute(channel -> {
        system.out.println(channel.getClass());
        return null;
    }
    

    If you don't see PublisherCallbackChannelImpl then it means the configuration didn't work for some reason. Again DEBUG logging should help with the configuration debugging.

    If you still can't figure it out, strip your application to the bare minimum that exhibits the behavior and post the complete application.