RabbitMQ速通--03整合SpringBoot

RabbitMQ整合SpringBoot

rabbitmq-demo(maven)
|__rabbitmq-demo-consumer(boot)
|__rabbitmq-demo_producer(boot)
<!-- 两个子模块的pom.xml -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.4.4</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>


<dependencies>
    <!-- rabbitmq整合springboot启动环境 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-amqp</artifactId>
    </dependency>
    
    <!-- 这个例子中只有消费者需要导入web场景来持续监听队列 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>
# 两个子模块的application.yml
# rabbitmq的相关配置
spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
    virtual-host: /
    listener:
      simple:
        prefetch: 1 #该配置表明每次只能从队列中取出1条消息
// 消费者模块
@Component
@Slf4j
public class MyMessageListener {

// 定义rabbitmq的队列,交换机,路由键等信息
 public static final String EXCHANGE_DIRECT = "exchange.direct.order";
 public static final String ROUTING_KEY = "order";
 public static final String QUEUE_NAME = "queue.order";

 // 使用该注解不只是监听还会在目标队列、交换机不存在时对其进行创建
 // @RabbitListener(bindings = @QueueBinding(
 //         // 指定队列名称;开启持久化
 //         value = @Queue(value = QUEUE_NAME,durable = "true"),
 //         // 指定交换机名称
 //         exchange = @Exchange(value = EXCHANGE_DIRECT),
 //         // 指定路由键(这里模拟的是路由模式)
 //         key = {ROUTING_KEY}))
 // 使用该注解可以直接监听目标队列
 @RabbitListener(queues = QUEUE_NAME)
 public void processMessage(
         String dateString,
         Message message ,
         Channel channel) {
     log.info(dateString);

 }
}
//生产者模块
@SpringBootTest
class RabbitmqDemoProducerApplicationTests {

    public static final String EXCHANGE_DIRECT = "exchange.direct.order";
    public static final String ROUTING_KEY = "order";
    public static final String QUEUE_NAME = "queue.order";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSendMessage(){
        rabbitTemplate.convertAndSend(EXCHANGE_DIRECT, ROUTING_KEY, "Hello World");
    }
}

创建完工程后,先启动消费者端对队列进行监听,再通过生产者模块发送消息,此时消费者端会接收到该消息。该变化也可以在rabbitmq的控制面板中查看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值