天天看點

SpringBoot使用ActiveMQ發送和接收消息(點對點模式)

作者:長頸鹿睡覺

JMS定義了兩種消息模式,點對點模式和釋出訂閱模式。

點對點模式

允許一個用戶端基于抽象模型queue給另一個用戶端發送消息。首先,發送消息的用戶端要将消息發送給特定的queue,然後,接收消息的用戶端從這個特定的queue接收消息。

釋出訂閱模式

允許一個用戶端基于抽象模型topic給多個用戶端發送消息。首先,發送消息的用戶端将消息釋出到特定的topic上,然後這個消息将被傳遞到所有訂閱了這個topic的用戶端上。

使用ActiveMQ的點對點模式進行發送和接收消息的過程如下:

導入ActiveMQ依賴

在SpringBoot的pom檔案中,引入ActiveMQ依賴。

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

配置ActiveMQ位址

在application.yml中配置ActiveMQ的位址。

spring:
  activemq:
    broker-url: tcp://localhost:61616           

注入JMS操作對象

使用@Autowired注解注入JmsMessagingTemplate對象,用來發送和接受消息。

@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;           

發送消息

使用convertAndSend方法發送消息。

第一個參數是消息隊列名,第二個參數是要發送的消息,可以傳入任意對象。

jmsMessagingTemplate.convertAndSend("process1","my message");           

接收消息

使用receiveAndConvert方法接收消息。

第一個參數是消息隊列名,第二個參數是消息的類名。

String msg = jmsMessagingTemplate.receiveAndConvert("process1",String.class);           

使用監聽器接收消息

使用 receiveAndConvert進行消息的處理,效率很低,需要主動去調用這個方法才能處理消息,如果消息隊列中沒有消息,則這個方法會阻塞。

使用監聽器是更高效的消息處理方式,隻要消息隊列中有待處理的消息,監聽器就會被調用,進行消息的處理。

定義消息處理的方法,方法參數是消息内容。

在方法上使用@JmsListener注解,通過destination參數指定消息隊列名。

@Component
public class ActiveMQListener {

    @JmsListener(destination = "process1")
    public void handleMsg(String msg){
        System.out.println(msg);
    }
}           

消息轉發

使用 @SendTo注解可以在處理完消息後,再次發送新消息到消息隊列,注解參數是要轉發的消息隊列名稱。

注意在使用@SendTo注解時,方法一定要有傳回值,因為轉發到新隊列的消息就是方法的傳回值。

@Component
public class ActiveMQListener {

    @JmsListener(destination = "process1")
    @SendTo("process2")
    public String handleMsg(String msg){
        System.out.println(msg);
        return msg;
    }
}           

消息隊列狀态

在ActiveMQ的管理頁面中,Queues菜單下能看到點對點模式下,消息隊列的情況。

SpringBoot使用ActiveMQ發送和接收消息(點對點模式)

測試

使用Spring Task定時發送消息到消息隊列。

@Component
@EnableScheduling
public class MsgTask {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Scheduled(fixedDelay = 2000)
    public void sendMsg(){
        jmsMessagingTemplate.convertAndSend("process1","my message");
    }

}           

使用監聽器接收處理消息,并轉發到新隊列。

@Component
public class ActiveMQListener {


    @JmsListener(destination = "process1")
    @SendTo("process2")
    public String handleMsg(String msg){
        System.out.println(msg);
        return msg;
    }
}           

啟動應用後,在控制台能看到監聽器一直在列印處理消息的資訊。

SpringBoot使用ActiveMQ發送和接收消息(點對點模式)

管理頁面能看到process1消息隊列的情況,和轉發的新消息隊列process2的情況

SpringBoot使用ActiveMQ發送和接收消息(點對點模式)