Springboot整合ActiveMQ
一、ActiveMQ的安装
1. 下载地址
ActiveMQhttps://activemq.apache.org/download-archives
2. 安装
下载后的压缩包(apache-activemq-5.15.8-bin.zip)解压缩就可以
3. 启动服务
3.1 D:\Software\activemq\bin\win64目录下的activemq.bat双击启动服务
这样代表成功。也可以在浏览器中请求http://localhost:8161/
3.2 activemq启动报错
WrapperSimpleApp: Unable to locate the class org.apache.activemq.console.Main: java.lang.Unsupported
说明 ActiveMQ的版本与java的版本不兼容,换成低版本的ActiveMQ。我就是遇到ActiveMQ 5.17.2 Release 版本报此错,换成apache-activemq-5.15.8版本就不再抛异常。
二、 Springboot整合ActiveMQ步骤
2.1 导入坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
2.2 配置
spring:
activemq:
broker-url: tcp://127.0.0.1:61616
jms:
pub-sub-domain: true #开启发布订阅模式,默认不开启
2.3 生产者与消费者消息(使用默认消息存储队列)
@Service
public class MessageServiceActiveMqImpl implements MessageService {
@Autowired
private JmsMessagingTemplate messagingTemplate; //消息的类
@Override
public void sendMessage(String id) {
//生产消息
messagingTemplate.convertAndSend("order.queue.id",id); //convertAndSend把生产的消息转化成统一格式
System.out.println("待发送短信订单:"+id);
}
@Override
public String getMessage() {
//receiveAndConvert接收消息,这是单个手动接收,一般使用监听器对消息队列进行接收
String id = messagingTemplate.receiveAndConvert("order.queue.id",String.class);//把消费的消息转化成指定的格式
System.out.println("订单短信发送完成:"+id);
return id;
}
}
public void convertAndSend(String destinationName, Object payload) throws MessagingException {
this.convertAndSend(destinationName, payload, (Map)null);
}
/*注:第一个参数表示消息来源,自己命名,生产和消费需要是同一个;
第二个参数表示消息
*/
@Nullable
public <T> T receiveAndConvert(String destinationName, Class<T> targetClass) throws MessagingException {
Message<?> message = this.doReceive(destinationName);
return message != null ? this.doConvert(message, targetClass) : null;
}
2.4 使用消息监听器对消息队列监听
在service包下建立listener包,创建MessageListener类。收到消息后自动消费。
@Component //Spring管理
@Slf4j
public class MessageListener {
@JmsListener(destination = "order.queue.id")
public void receive(String id){
System.out.println("已完成短信发送业务,id:" + id);
log.info("已完成短信发送业务,id:" + id);
}
}
三、生产和消费的消息状态
生产和消费的消息状态都可以在http://127.0.0.1:8161/admin/
的queues或topics菜单下查询到,取决于pub-sub-domain: true #开启发布订阅模式,默认不开启。不开启在queues下。开启在topics下
还没有评论,来说两句吧...