RabbitMQ: return与confirm 机制整合 spirngboot实现

package com.qf.mq2203.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class RabbitmqConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        // 设置 return callback
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {

            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {

                System.out.println(Thread.currentThread().getName() + "================");
                final byte[] body = message.getBody(); // 消息的内容
                System.out.println(message);
                System.out.println(replyCode);
                System.out.println(replyText);
                System.out.println(exchange);
                System.out.println(routingKey);

                System.out.println(Thread.currentThread().getName() + "================");

            }
        });

        // 设置 confirm回调方法
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println(Thread.currentThread().getName() + "----------------");

                System.out.println(correlationData);
                System.out.println(ack);
                System.out.println(cause);

                System.out.println(Thread.currentThread().getName() + "----------------");
            }
        });
    }


    @Bean
    public TopicExchange topicExchange() {
        final TopicExchange topicExchange = new TopicExchange("boot-topic-exchange", true, false);
        return topicExchange;
    }

    @Bean
    public Queue queue() {
        final Queue queue = new Queue("boot-queue");
        return queue;
    }

    @Bean
    public Binding binding(Queue queue, TopicExchange topicExchange) {

        String routingkey = "*.red.*";
        final Binding binding = BindingBuilder.bind(queue).to(topicExchange).with(routingkey);
        return binding;

    }

}

yml

spring:
  rabbitmq:
    host: 39.98.95.55
    port: 5672
    virtual-host: /test
    username: test
    password: test
    listener:
      simple:
        prefetch: 1
        acknowledge-mode: manual
    publisher-returns: true  # 开启mq的return机制
    publisher-confirm-type: correlated

你可能感兴趣的:(RabbitMQ,java-rabbitmq,rabbitmq,java)