Springboot整合ActiveMQ

左手的ㄟ右手 2023-10-07 21:08 133阅读 0赞

一、ActiveMQ的安装

1. 下载地址

ActiveMQfavicon.pnghttps://activemq.apache.org/download-archives

2. 安装

下载后的压缩包(apache-activemq-5.15.8-bin.zip)解压缩就可以

3. 启动服务

3.1 D:\Software\activemq\bin\win64目录下的activemq.bat双击启动服务

7e9dca113c3b46599c1fac39cab6dab8.png

这样代表成功。也可以在浏览器中请求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 导入坐标

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-activemq</artifactId>
  4. </dependency>

2.2 配置

  1. spring:
  2. activemq:
  3. broker-url: tcp://127.0.0.1:61616
  4. jms:
  5. pub-sub-domain: true #开启发布订阅模式,默认不开启

2.3 生产者与消费者消息(使用默认消息存储队列)

  1. @Service
  2. public class MessageServiceActiveMqImpl implements MessageService {
  3. @Autowired
  4. private JmsMessagingTemplate messagingTemplate; //消息的类
  5. @Override
  6. public void sendMessage(String id) {
  7. //生产消息
  8. messagingTemplate.convertAndSend("order.queue.id",id); //convertAndSend把生产的消息转化成统一格式
  9. System.out.println("待发送短信订单:"+id);
  10. }
  11. @Override
  12. public String getMessage() {
  13. //receiveAndConvert接收消息,这是单个手动接收,一般使用监听器对消息队列进行接收
  14. String id = messagingTemplate.receiveAndConvert("order.queue.id",String.class);//把消费的消息转化成指定的格式
  15. System.out.println("订单短信发送完成:"+id);
  16. return id;
  17. }
  18. }
  19. public void convertAndSend(String destinationName, Object payload) throws MessagingException {
  20. this.convertAndSend(destinationName, payload, (Map)null);
  21. }
  22. /*注:第一个参数表示消息来源,自己命名,生产和消费需要是同一个;
  23. 第二个参数表示消息
  24. */
  25. @Nullable
  26. public <T> T receiveAndConvert(String destinationName, Class<T> targetClass) throws MessagingException {
  27. Message<?> message = this.doReceive(destinationName);
  28. return message != null ? this.doConvert(message, targetClass) : null;
  29. }

2.4 使用消息监听器对消息队列监听

在service包下建立listener包,创建MessageListener类。收到消息后自动消费。

  1. @Component //Spring管理
  2. @Slf4j
  3. public class MessageListener {
  4. @JmsListener(destination = "order.queue.id")
  5. public void receive(String id){
  6. System.out.println("已完成短信发送业务,id:" + id);
  7. log.info("已完成短信发送业务,id:" + id);
  8. }
  9. }

三、生产和消费的消息状态

生产和消费的消息状态都可以在http://127.0.0.1:8161/admin/
的queues或topics菜单下查询到,取决于pub-sub-domain: true #开启发布订阅模式,默认不开启。不开启在queues下。开启在topics下

1bcc4b8359a647f9b0c832c71122eaac.png

f301d1ccaf794f8cb786ca0de6d65ff2.png

发表评论

表情:
评论列表 (有 0 条评论,133人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot整合ActiveMQ

    前言   ActiveMQ 一个成熟的消息中间件,作用于系统之间的通信,降低模块与模块之间的耦合度。   消息的传递有两种类型: 1. Queue 队列模式:一个生