Spring Boot与ActiveMQ的集成

时间:2023-03-08 23:37:33
Spring Boot与ActiveMQ的集成

  Spring Boot对JMS(Java Message Service,Java消息服务)也提供了自动配置的支持,其主要支持的JMS实现有ActiveMQ、Artemis等。本节中,将以ActiveMQ为例来讲解下Spring Boot与ActiveMQ的集成使用。

  在Spring Boot中,已经内置了对ActiveMQ的支持。要在Spring Boot项目中使用ActiveMQ,只需在pom.xml中添加ActiveMQ的起步依赖即可。

  添加ActiveMQ起步依赖:

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

  创建消息队列对象:
  在Application.java中编写一个创建消息队列的方法,其代码如下所示。

/**
* 创建消息队列的方法
*/
@Bean
public Queue queue() {
return new ActiveMQQueue("active.queue");
}

  创建消息生产者:
  创建一个队列消息的控制器类QueueController,并在类中编写发送消息的方法

package com.xc.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import javax.jms.Queue; /**
* 队列消息的控制器类QueueController
*/
@RestController
public class QueueController { @Autowired
private JmsMessagingTemplate jmsMessagingTemplate; @Autowired
private Queue queue; /**
* 消息生产者
*/
@RequestMapping("/send")
public void send() {
// 指定消息发送的目的地及内容
jmsMessagingTemplate.convertAndSend(queue, "新发送的消息!");
} }

  创建消息监听者:
  创建一个客户控制器类CustomerController,并在类中编写监听和读取消息的方法

package com.xc.springboot.controller;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.web.bind.annotation.RestController; /**
* 客户控制器
*/
@RestController
public class CustomerController { /**
* 监听和读取消息
*/
@JmsListener(destination = "active.queue")
public void readActiveQueue(String message) {
System.out.println("接收到:" + message);
}
}

  在上述代码中,@JmsListener是Spring 4.1所提供的用于监听JMS消息的注解,该注解的属性destination用于指定要监听的目的地。本案例中监听的是active.queue中的消息。

  启动项目,测试应用:
  启动Spring Boot项目,在浏览器中输入地址http://localhost:8081/send后,控制台将显示所接收到的消息

接收到:新发送的消息!

  在实际开发中,ActiveMQ可能是单独部署在其他机器上的,如果要使用它,就需要实现对它的远程调用。要使用远程中的ActiveMQ其实很简单,只需在配置文件中指定ActiveMQ的远程主机地址以及服务端口号,其配置代码如下:

spring.activemq.broker-url=tcp://192.168.2.100:61616

  在上述配置中,192.168.2.100是远程主机的IP地址,61616是ActiveMQ的服务端口号。