Spring Boot整合RabbitMQ (手动应答模式)

手动应答模式

  • 第1步,编写application.properties
spring.rabbitmq.host = 127.0.0.1
spring.rabbitmq.port = 5672
spring.rabbitmq.password = test
spring.rabbitmq.username = test
spring.rabbitmq.virtual-host = /test
# 手动应答模式下,开启消息回调功能
spring.rabbitmq.publisher-confirms = true
spring.rabbitmq.publisher-returns = true
  • 第2步,编写RabbitMQ配置
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * RabbitMQ配置
 */
@Configuration
public class SpringBootRabbitMQConfiguration2 {


    // ======== 生产者配置 ========

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Bean
    public AmqpTemplate amqpTemplate() {
        // 必须开启回调才会生效
        rabbitTemplate.setMandatory(true);
        // 消息确认,需要配置 spring.rabbitmq.publisher-returns = true
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("------------------------------------------------");
            System.out.println("ConfirmCallBackListener:correlationData=" + correlationData + ",ack=" + ack + ",cause=" + cause);
            System.out.println("------------------------------------------------");
        });
        // 消息发送失败返回到队列中,需要配置spring.rabbitmq.publisher-confirms = true
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("------------------------------------------------");
            System.out.println("ReturnCallBackListener:message=" + new String(message.getBody()) + ",replyCode=" + replyCode + ",replyText=" + replyText + ",exchange=" + exchange + ",routingKey=" + routingKey);
            System.out.println("------------------------------------------------");
        });
        return rabbitTemplate;
    }

    /**
     * 声明了一个TopicExchange
     *
     * @return
     */
    @Bean
    public TopicExchange myExchange() {
        return new TopicExchange("myExchange");
    }


    // ======== 消费者配置 ========

    /**
     * 声明了一个Queue
     *
     * @return
     */
    @Bean
    public Queue myQueue() {
        return new Queue("myQueue");
    }


    // ======== 实际项目中为了解耦,绑定队列是放在RabbitMQ的Web端操作========

    /**
     * 队列1绑定TopicExchange并关联到RoutingKey
     *
     * @param myQueue
     * @param myExchange
     * @return
     */
    @Bean
    public Binding bindingMyQueueToTestTopicExchange(@Qualifier("myQueue") Queue myQueue, @Qualifier("myExchange") TopicExchange myExchange) {
        return BindingBuilder.bind(myQueue).to(myExchange).with("foo.*");
    }

}
  • 第3步,编写消费者类
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

/**
 * 消费者确认消息
 */
@Component("springBoot2Consumer")
public class Consumer {

    @RabbitListener(queues = "myQueue")
    public void onMessage(Message message, Channel channel) throws Exception {
        try {
            System.out.println("消费者: " + new String(message.getBody()));
            // 当消费者把消息消费成功,再手动应答RabbitMQ
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 第4步,编写生产者类
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 生产者发送消息,并得到消息送达情况
 */
@Component("springBoot2Producer")
public class Producer {

    public static final String EXCHANGE = "myExchange";
    public static final String ROUTING_KEY = "foo.bar";

    @Resource
    private AmqpTemplate amqpTemplate;

    /**
     * 情况1:exchange和routingKey都正确:ConfirmCallBackListener回调被执行,ack=true
     *
     * @throws InterruptedException
     */
    public void test1() throws InterruptedException {
        // 发送消息,指定交换机和路由标识
        amqpTemplate.convertAndSend(EXCHANGE, ROUTING_KEY, "Hello, world!!!");
    }

    /**
     * 情况2:exchange错误,routingKey正确:ConfirmCallBackListener回调被执行,ack=false
     *
     * @throws InterruptedException
     */
    public void test2() throws InterruptedException {
        // 故意乱指定了一个exchange,表达消息发送到exchange失败
        amqpTemplate.convertAndSend("aaa", ROUTING_KEY, "Hello, world!!!");
    }

    /**
     * 情况3:exchange正确,routingKey错误:ConfirmCallBackListener回调被执行,ack=true、ReturnCallBackListener回调被执行
     *
     * @throws InterruptedException
     */
    public void test3() throws InterruptedException {
        // 故意乱指定了一个routingKey,表达消息发送到queue失败
        amqpTemplate.convertAndSend(EXCHANGE, "bbb", "Hello, world!!!");
    }

    /**
     * 情况4:exchange和routingKey都错误:ConfirmCallBackListener回调被执行,ack=false
     *
     * @throws InterruptedException
     */
    public void test4() throws InterruptedException {
        // 故意乱指定了exchange和routingKey
        amqpTemplate.convertAndSend("aaa", "bbb", "Hello, world!!!");
    }
}
  • 第6步,编写测试类
/**
 * 生产者发送消息,并得到消息送达情况
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootRabbitMQTest2 {

    @Autowired
    @Qualifier("springBoot2Producer")
    private Producer producer;

    /**
     * 情况1:exchange和routingKey都正确:ConfirmCallBackListener回调被执行,ack=true
     *
     * @throws InterruptedException
     */
    @Test
    public void test1() throws InterruptedException {
        producer.test1();
    }

    /**
     * 情况2:exchange错误,routingKey正确:ConfirmCallBackListener回调被执行,ack=false
     *
     * @throws InterruptedException
     */
    @Test
    public void test2() throws InterruptedException {
        producer.test2();
    }

    /**
     * 情况3:exchange正确,routingKey错误:ConfirmCallBackListener回调被执行,ack=true、ReturnCallBackListener回调被执行
     *
     * @throws InterruptedException
     */
    @Test
    public void test3() throws InterruptedException {
        producer.test3();
    }

    /**
     * 情况4:exchange和routingKey都错误:ConfirmCallBackListener回调被执行,ack=false
     *
     * @throws InterruptedException
     */
    @Test
    public void test4() throws InterruptedException {
        producer.test4();
    }

}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring BootRabbitMQ整合可以通过使用Spring AMQP实现。下面是一个简单的步骤: 1. 添加依赖:在`pom.xml`文件中添加以下依赖关系: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 2. 配置RabbitMQ连接:在`application.properties`或`application.yml`文件中配置RabbitMQ的连接信息,例如: ```properties spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest ``` 3. 创建生产者:创建一个简单的生产者,用于向RabbitMQ发送消息。你可以使用`RabbitTemplate`类来发送消息,例如: ```java import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MessageProducer { @Autowired private RabbitTemplate rabbitTemplate; public void sendMessage(String message) { rabbitTemplate.convertAndSend("exchangeName", "routingKey", message); } } ``` 4. 创建消费者:创建一个简单的消费者,用于接收RabbitMQ发送的消息。你可以使用`@RabbitListener`注解来定义一个消息监听器,例如: ```java import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class MessageConsumer { @RabbitListener(queues = "queueName") public void receiveMessage(String message) { System.out.println("Received message: " + message); } } ``` 5. 启用RabbitMQ:通过在Spring Boot应用程序的主类上添加`@EnableRabbit`注解来启用RabbitMQ功能,例如: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.amqp.rabbit.annotation.EnableRabbit; @SpringBootApplication @EnableRabbit public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 这就是整合Spring BootRabbitMQ的基本步骤。你可以根据自己的需求进行更多的高级配置和定制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值