首页 > 其他分享 >SpringBoot整合ActiveMQ的详细步骤

SpringBoot整合ActiveMQ的详细步骤

时间:2023-01-30 18:12:57浏览次数:36  
标签:ActiveMQ SpringBoot spring 步骤 topic 消息 import org activemq

pom文件引入activemq依赖

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <!--activeMq配置-->     <dependency>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-starter-activemq</artifactId>     </dependency>     <dependency>         <groupId>org.apache.activemq</groupId>         <artifactId>activemq-pool</artifactId>         <version>5.15.3</version>     </dependency>       <dependency>         <groupId>org.projectlombok</groupId>         <artifactId>lombok</artifactId>     </dependency>     <dependency>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-starter-web</artifactId>     </dependency>     <dependency>         <groupId>com.alibaba</groupId>         <artifactId>fastjson</artifactId>         <version>2.0.7</version>     </dependency>

2. 配置文件

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 spring:   activemq:     user: admin     password: admin     broker-url: failover:(tcp://192.168.43.666:61616)     #是否信任所有包(如果传递的是对象则需要设置为true,默认是传字符串)     packages:       trust-all: true     #连接池     pool:       enabled: true       max-connections: 5       idle-timeout: 30000 #      expiry-timeout: 0     jms:       #默认使用queue模式,使用topic则需要设置为true       pub-sub-domain: true         # 是否信任所有包       #spring.activemq.packages.trust-all=       # 要信任的特定包的逗号分隔列表(当不信任所有包时)       #spring.activemq.packages.trusted=       # 当连接请求和池满时是否阻塞。设置false会抛“JMSException异常”。       #spring.activemq.pool.block-if-full=true       # 如果池仍然满,则在抛出异常前阻塞时间。       #spring.activemq.pool.block-if-full-timeout=-1ms       # 是否在启动时创建连接。可以在启动时用于加热池。       #spring.activemq.pool.create-connection-on-startup=true       # 是否用Pooledconnectionfactory代替普通的ConnectionFactory。       #spring.activemq.pool.enabled=false       # 连接过期超时。       #spring.activemq.pool.expiry-timeout=0ms       # 连接空闲超时       #spring.activemq.pool.idle-timeout=30s       # 连接池最大连接数       #spring.activemq.pool.max-connections=1       # 每个连接的有效会话的最大数目。       #spring.activemq.pool.maximum-active-session-per-connection=500       # 当有"JMSException"时尝试重新连接       #spring.activemq.pool.reconnect-on-exception=true       # 在空闲连接清除线程之间运行的时间。当为负数时,没有空闲连接驱逐线程运行。       #spring.activemq.pool.time-between-expiration-check=-1ms       # 是否只使用一个MessageProducer       #spring.activemq.pool.use-anonymous-producers=true

3. 生产者

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 package com.gblfy.producer;   import org.apache.activemq.ScheduledMessage; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.jms.JmsProperties; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;   import javax.jms.*; import java.io.Serializable;   /**  * 发送消息  *  * @author gblfy  * @date 2022-11-02  */ @RestController @RequestMapping(value = "/active") public class SendController {     //也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装     @Autowired     private JmsMessagingTemplate jmsMessagingTemplate;       /**      * 发送消息接口      * 发送queue消息 :http://127.0.0.1:8080/active/send?msg=ceshi1234      * 发送topic 消息: http://127.0.0.1:8080/active/topic/send?msg=ceshi1234      * 发送queue消息(延迟time毫秒) :http://127.0.0.1:8080/active/send?msg=ceshi1234&time=5000      *      * @param msg  消息      * @param type url中参数,非必须      * @param time      * @return      */     @RequestMapping({"/send", "/{type}/send"})     public String send(@PathVariable(value = "type", required = false) String type, String msg, Long time) {         Destination destination = null;         if (type == null) {             type = "";         }         switch (type) {             case "topic":                 //发送广播消息                 destination = new ActiveMQTopic("active.topic");                 break;             default:                 //发送 队列消息                 destination = new ActiveMQQueue("active.queue");                 break;         }         // System.out.println("开始请求发送:"+DateUtil.getStringDate(new Date(),"yyyy-MM-dd HH:mm:ss"));         if (time != null && time > 0) {             //延迟队列,延迟time毫秒             //延迟队列需要在 <broker>标签上增加属性 schedulerSupport="true"             delaySend(destination, msg, time);         } else {             jmsMessagingTemplate.convertAndSend(destination, msg);//无序             //jmsMessagingTemplate.convertSendAndReceive();//有序         }         return "activemq消息发送成功 队列消息:" + msg;     }       /**      * 延时发送      * 说明:延迟队列需要在 <broker>标签上增加属性 schedulerSupport="true"      *      * @param destination 发送的队列      * @param data        发送的消息      * @param time        延迟时间 /毫秒      */     public <T extends Serializable> void delaySend(Destination destination, T data, Long time) {         Connection connection = null;         Session session = null;         MessageProducer producer = null;         // 获取连接工厂         ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();         try {             // 获取连接             connection = connectionFactory.createConnection();             connection.start();             // 获取session,true开启事务,false关闭事务             session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);             // 创建一个消息队列             producer = session.createProducer(destination);             producer.setDeliveryMode(JmsProperties.DeliveryMode.PERSISTENT.getValue());             ObjectMessage message = session.createObjectMessage(data);             //设置延迟时间             message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);             // 发送消息             producer.send(message);             session.commit();         } catch (Exception e) {             e.printStackTrace();         } finally {             try {                 if (producer != null) {                     producer.close();                 }                 if (session != null) {                     session.close();                 }                 if (connection != null) {                     connection.close();                 }             } catch (Exception e) {                 e.printStackTrace();             }         }     } }

4. 配置config

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 package com.gblfy.config;   import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.activemq.RedeliveryPolicy; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.ActiveMQTopic; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jms.annotation.EnableJms; import org.springframework.jms.config.DefaultJmsListenerContainerFactory; import org.springframework.jms.config.JmsListenerContainerFactory;   import javax.jms.Queue; import javax.jms.Topic;   /**  * 描述:  * activemq 有两种模式 queue 和 topic  * queue 模式是单对单,有多个消费者的情况下则是使用轮询监听  * topic 模式/广播模式/发布订阅模式 是一对多,发送消息所有的消费者都能够监听到  *  * @author gblfy  * @date 2022-11-02  */ @EnableJms @Configuration public class ActiveMQConfig {     //队列名     private static final String queueName = "active.queue";     //主题名     private static final String topicName = "active.topic";       @Value("${spring.activemq.user:}")     private String username;     @Value("${spring.activemq.password:}")     private String password;     @Value("${spring.activemq.broker-url:}")     private String brokerUrl;       @Bean     public Queue acQueue() {         return new ActiveMQQueue(queueName);     }       @Bean     public Topic acTopic() {         return new ActiveMQTopic(topicName);     }       @Bean     public ActiveMQConnectionFactory connectionFactory() {         return new ActiveMQConnectionFactory(username, password, brokerUrl);     }       @Bean     public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ActiveMQConnectionFactory connectionFactory) {         DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();         // 关闭Session事务,手动确认与事务冲突         bean.setSessionTransacted(false);         // 设置消息的签收模式(自己签收)         /**          * AUTO_ACKNOWLEDGE = 1 :自动确认          * CLIENT_ACKNOWLEDGE = 2:客户端手动确认          * DUPS_OK_ACKNOWLEDGE = 3: 自动批量确认          * SESSION_TRANSACTED = 0:事务提交并确认          * 但是在activemq补充了一个自定义的ACK模式:          * INDIVIDUAL_ACKNOWLEDGE = 4:单条消息确认          **/         bean.setSessionAcknowledgeMode(4);         //此处设置消息重发规则,redeliveryPolicy() 中定义         connectionFactory.setRedeliveryPolicy(redeliveryPolicy());         bean.setConnectionFactory(connectionFactory);         return bean;     }       @Bean     public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ActiveMQConnectionFactory connectionFactory) {         DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();         // 关闭Session事务,手动确认与事务冲突         bean.setSessionTransacted(false);         bean.setSessionAcknowledgeMode(4);         //设置为发布订阅方式, 默认情况下使用的生产消费者方式         bean.setPubSubDomain(true);         bean.setConnectionFactory(connectionFactory);         return bean;     }       /**      * 消息的重发规则配置      */     @Bean     public RedeliveryPolicy redeliveryPolicy() {         RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();         // 是否在每次尝试重新发送失败后,增长这个等待时间         redeliveryPolicy.setUseExponentialBackOff(true);         // 重发次数五次, 总共六次         redeliveryPolicy.setMaximumRedeliveries(5);         // 重发时间间隔,默认为1000ms(1秒)         redeliveryPolicy.setInitialRedeliveryDelay(1000);         // 重发时长递增的时间倍数2         redeliveryPolicy.setBackOffMultiplier(2);         // 是否避免消息碰撞         redeliveryPolicy.setUseCollisionAvoidance(false);         // 设置重发最大拖延时间-1表示无延迟限制         redeliveryPolicy.setMaximumRedeliveryDelay(-1);         return redeliveryPolicy;     } }

5. queue消费者

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 package com.gblfy.listener;   import org.apache.activemq.command.ActiveMQMessage; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component;   import javax.jms.JMSException; import javax.jms.Session;   /**  * TODO  *  * @author gblfy  * @Date 2022-11-02  **/ @Component public class QueueListener {       /**      * queue 模式 单对单,两个消费者监听同一个队列则通过轮询接收消息      * containerFactory属性的值关联config类中的声明      *      * @param msg      */     @JmsListener(destination = "active.queue", containerFactory = "jmsListenerContainerQueue")     public void queueListener(ActiveMQMessage message, Session session, String msg) throws JMSException {         try {             System.out.println("active queue 接收到消息 " + msg);             //手动签收             message.acknowledge();         } catch (Exception e) {             //重新发送             session.recover();         }     } }

6. topic消费者

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 package com.gblfy.listener;   import org.apache.activemq.command.ActiveMQMessage; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component;   import javax.jms.JMSException; import javax.jms.Session;   /**  * TODO  *  * @author gblfy  * @Date 2022-11-02  **/ @Component public class TopicListener {       /**      * topic 模式/广播模式/发布订阅模式 一对多,多个消费者可同时接收到消息      * topic 模式无死信队列,死信队列是queue模式      * containerFactory属性的值关联config类中的声明      *      * @param msg      */     @JmsListener(destination = "active.topic", containerFactory = "jmsListenerContainerTopic")     public void topicListener(ActiveMQMessage message, Session session, String msg) throws JMSException {         try {             // System.out.println("接收到消息:" + DateUtil.getStringDate(new Date(), "yyyy-MM-dd HH:mm:ss"));             System.out.println("active topic 接收到消息 " + msg);             System.out.println("");             //手动签收             message.acknowledge();         } catch (Exception e) {             //重新发送             session.recover();         }     }       @JmsListener(destination = "active.topic", containerFactory = "jmsListenerContainerTopic")     public void topicListener2(ActiveMQMessage message, Session session, String msg) throws JMSException {         try {             // System.out.println("接收到消息:" + DateUtil.getStringDate(new Date(), "yyyy-MM-dd HH:mm:ss"));             System.out.println("active topic2 接收到消息 " + msg);             System.out.println("");             //手动签收             message.acknowledge();         } catch (Exception e) {             //重新发送             session.recover();         }     } }

6. ActiveMQ 消息存储规则

QUEUE 点对点:

特点:消息遵循先到先得,消息只能被一个消费者消费。

消息存储规则:消费者消费消息成功,MQ服务端消息删除

TOPIC订阅模式: 消息属于广播(订阅)模式,消息会被所有的topic消费者消费消息。

消息存储规则:所有消费者消费成功,MQ服务端消息删除,有一个消息没有没有消费完成,消息也会存储在MQ服务端。

举例:

已经处于运行topic消费者5个,5个消费者消费完成后,MQ服务端消息删除。

扩展点补充:如果想额外添加topic消费者,如果MQ服务端消息没有被消费完毕,新增topic消费者可以消费以前未被消费的消息,
正常新增的只会消费新的topic消息。

标签:ActiveMQ,SpringBoot,spring,步骤,topic,消息,import,org,activemq
From: https://www.cnblogs.com/telwanggs/p/17076887.html

相关文章

  • springboot配置activemq
    前言网上有好多介绍springboot集成activemq的文章,看了一些文章感觉比较零散,还是抽时间自己详细总结一个如何使用,需要注意哪些点。尤其是关于连接池的配置,需要重点关注,否则......
  • springboot整合activemq(三)配置文件
    #服务端口,8080被另一服务占用server.port=9090spring.activemq.broker-url=tcp://127.0.0.1:61616#在考虑结束之前等待的时间#spring.activemq.close-timeout=15s#默认代......
  • 随笔(十五)『SpringBoot 整合 Redis』
    一、添加依赖<!--redis启动器--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>......
  • springboot集成swagger的坑
    1、端口问题无法访问此网站网址为 http://localhost:6666/swagger-ui.html 的网页可能暂时无法连接,或者它已永久性地移动到了新网址。ERR_UNSAFE_PORT 如图:......
  • 戴维南定理的理论解释及求解步骤
    内容:对外电路来说,任何一个线性有源二端网络,均可以用一个理想电压源和一个电阻元件串联的有源支路来等效代替,其电压源US等于线性有源二端网络的开路电压UOC,电阻元件的阻值R0......
  • springboot~openfeign开启熔断之后MDC为null的解决
    上一篇说了关于MDC跨线程为null的理解,而本讲主要说一下,如何去解决它,事实上,Hystrix为我们留了这个口,我们只需要继承HystrixConcurrencyStrategy,然后重写wrapCallable方法,再......
  • CAD系统变量怎么修改?CAD系统变量修改步骤
    在浩辰CAD软件中存在着大量系统变量,绝大多数是在后台默默发挥作用,但有些CAD系统变量在绘图过程中也会用到,比如FILEDIA、TEXTFILL等。那CAD系统变量怎么修改?本文小编就来给......
  • CAD怎么把图形分割?CAD图形分割方法步骤
    如何进行CAD图形分割?在进行CAD图纸绘制的过程中,有些时候会需要我们从一整张CAD图纸中分割出一部分来使用,这种时候要怎么进行CAD图形分割呢?如果你还不会的话,就来看看下面小......
  • CAD中怎么旋转光标?CAD旋转光标的方法步骤
    CAD中怎么旋转光标?浩辰CAD软件作为一款拥有自主核心技术的CAD平台软件产品,提供了CAD旋转光标命令,本节课程就和小编一起来了解一下浩辰CAD软件中CAD旋转光标的方法步骤吧!CA......
  • CAD怎么导入系统设置文件?浩辰CAD系统设置文件导入步骤
    很多设计师小伙伴换电脑后重新安装了浩辰CAD软件,但是想要将给之前的CAD系统设置文件导入到新电脑的浩辰CAD软件中,这种情况该怎么办呢?本节教程小编就来给大家分享一下浩辰CA......