Spring Boot 集成 RabbitMQ 非常简单,如果只是简单的使用配置非常少,Spring Boot 提供了spring-boot-starter-amqp 项目对消息各种支持。

简单使用

1、pom.xml 文件添加 spring-boot-starter-amqp 依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2、配置文件

配置 RabbitMQ 的安装地址、端口以及账户信息

spring:
  # Rabbitmq 配置
  rabbitmq:
    host: 192.168.31.100
    port: 5672
    username: admin
    password: admin
    virtual-host: /
    publisher-confirm-type: simple
    #启动消息失败返回,比如路由不到队列时触发回调
    publisher-returns: true
    listener:
      simple:
        #NONE:自动确认;AUTO:根据情况确认;MANUAL:手动确认
        acknowledge-mode: auto
      direct:
        #NONE:自动确认;AUTO:根据情况确认;MANUAL:手动确认
        acknowledge-mode: auto

3、队列配置

@Configuration
public class RabbitConfig {

    @Bean
    public Queue Queue() {
        return new Queue("hello");
    }
}

4、生产者

rabbitTemplate 是 Spring Boot 提供的默认实现

@component
public class HelloSender {

    @Autowired
    private AmqpTemplate rabbitTemplate;

    public void send() {
        String context = "hello " + new Date();
        System.out.println("Sender : " + context);
        this.rabbitTemplate.convertAndSend("hello", context);
    }
}

5、消费者

@Component
@RabbitListener(queues = "hello")
public class HelloReceiver {

    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver  : " + hello);
    }
}

6、测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitMqHelloTest {

    @Autowired
    private HelloSender helloSender;

    @Test
    public void hello() throws Exception {
        helloSender.send();
    }
}

注意:发送者和接收者的 queue name 必须一致,不然不能接收

参考资料:

https://blog.csdn.net/herry66/article/details/123422005

作者:Jeebiz  创建时间:2023-03-30 10:35
最后编辑:Jeebiz  更新时间:2024-09-23 10:03