天天看點

SpringAMQP Basic Queue消息發送和接收

SpringAMQP是基于RabbitMQ封裝的一套模闆,并且還利用SpringBoot對其實作了自動裝配,使用起來非常友善。

SpringAmqp的官方位址:https://spring.io/projects/spring-amqp

SpringAMQP提供了三個功能:

  • 自動聲明隊列、交換機及其綁定關系
  • 基于注解的監聽器模式,異步接收消息
  • 封裝了RabbitTemplate工具,用于發送消息

一.Basic Queue 簡單隊列模型

在項目中引入依賴

<!--AMQP依賴,包含RabbitMQ-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
      

  

1.消息發送

首先配置MQ位址,在publisher服務的application.yml中添加配置:

spring:
  rabbitmq:
    host: 127.0.0.1 # 主機名
    port: 5672 # 端口
    virtual-host: / # 虛拟主機
    username: mymq # 使用者名
    password: 123321 # 密碼
      

 

然後在publisher服務中編寫測試類SpringAmqpTest,并利用RabbitTemplate實作消息發送:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

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

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Test
    public void testSimpleQueue() {
        // 隊列名稱
        String queueName = "simple.queue";
        // 消息
        String message = "hello, spring amqp!";
        // 發送消息
        rabbitTemplate.convertAndSend(queueName, message);
    }
}
      

2.消息接收

首先配置MQ位址,在consumer服務的application.yml中添加配置:

spring:
  rabbitmq:
    host: 127.0.0.1 # 主機名
    port: 5672 # 端口
    virtual-host: / # 虛拟主機
    username: mymq # 使用者名
    password: 123321 # 密碼
      
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class SpringRabbitListener {

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueueMessage(String msg) throws InterruptedException {
        System.out.println("spring 消費者接收到消息:【" + msg + "】");
    }
}
      

3.測試