[JAVA] SpringBoot整合ActiveMQ的详细步骤

1846 0
黑夜隐士 2022-11-6 11:23:47 | 显示全部楼层 |阅读模式
目录

    1. 引入依赖2. 配置文件3. 生产者4. 配置config5. queue消费者6. topic消费者6. ActiveMQ 消息存储规则总结


1. 引入依赖

pom文件引入activemq依赖
  1.     <!--activeMq配置-->
  2.         <dependency>
  3.             <groupId>org.springframework.boot</groupId>
  4.             <artifactId>spring-boot-starter-activemq</artifactId>
  5.         </dependency>
  6.         <dependency>
  7.             <groupId>org.apache.activemq</groupId>
  8.             <artifactId>activemq-pool</artifactId>
  9.             <version>5.15.3</version>
  10.         </dependency>
  11.         <dependency>
  12.             <groupId>org.projectlombok</groupId>
  13.             <artifactId>lombok</artifactId>
  14.         </dependency>
  15.         <dependency>
  16.             <groupId>org.springframework.boot</groupId>
  17.             <artifactId>spring-boot-starter-web</artifactId>
  18.         </dependency>
  19.         <dependency>
  20.             <groupId>com.alibaba</groupId>
  21.             <artifactId>fastjson</artifactId>
  22.             <version>2.0.7</version>
  23.         </dependency>
复制代码
2. 配置文件
  1. spring:
  2.   activemq:
  3.     user: admin
  4.     password: admin
  5.     broker-url: failover:(tcp://192.168.43.666:61616)
  6.     #是否信任所有包(如果传递的是对象则需要设置为true,默认是传字符串)
  7.     packages:
  8.       trust-all: true
  9.     #连接池
  10.     pool:
  11.       enabled: true
  12.       max-connections: 5
  13.       idle-timeout: 30000
  14. #      expiry-timeout: 0
  15.     jms:
  16.       #默认使用queue模式,使用topic则需要设置为true
  17.       pub-sub-domain: true
  18.       # 是否信任所有包
  19.       #spring.activemq.packages.trust-all=
  20.       # 要信任的特定包的逗号分隔列表(当不信任所有包时)
  21.       #spring.activemq.packages.trusted=
  22.       # 当连接请求和池满时是否阻塞。设置false会抛“JMSException异常”。
  23.       #spring.activemq.pool.block-if-full=true
  24.       # 如果池依旧满,则在抛出异常前阻塞时间。
  25.       #spring.activemq.pool.block-if-full-timeout=-1ms
  26.       # 是否在启动时创建连接。可以在启动时用于加热池。
  27.       #spring.activemq.pool.create-connection-on-startup=true
  28.       # 是否用Pooledconnectionfactory代替普通的ConnectionFactory。
  29.       #spring.activemq.pool.enabled=false
  30.       # 连接过期超时。
  31.       #spring.activemq.pool.expiry-timeout=0ms
  32.       # 连接空闲超时
  33.       #spring.activemq.pool.idle-timeout=30s
  34.       # 连接池最大连接数
  35.       #spring.activemq.pool.max-connections=1
  36.       # 每个连接的有效会话的最大数目。
  37.       #spring.activemq.pool.maximum-active-session-per-connection=500
  38.       # 当有"JMSException"时尝试重新连接
  39.       #spring.activemq.pool.reconnect-on-exception=true
  40.       # 在空闲连接清除线程之间运行的时间。当为负数时,没有空闲连接驱逐线程运行。
  41.       #spring.activemq.pool.time-between-expiration-check=-1ms
  42.       # 是否只使用一个MessageProducer
  43.       #spring.activemq.pool.use-anonymous-producers=true
复制代码
3. 生产者
  1. package com.gblfy.producer;
  2. import org.apache.activemq.ScheduledMessage;
  3. import org.apache.activemq.command.ActiveMQQueue;
  4. import org.apache.activemq.command.ActiveMQTopic;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.autoconfigure.jms.JmsProperties;
  7. import org.springframework.jms.core.JmsMessagingTemplate;
  8. import org.springframework.web.bind.annotation.PathVariable;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RestController;
  11. import javax.jms.*;
  12. import java.io.Serializable;
  13. /**
  14. * 发送消息
  15. *
  16. * @author gblfy
  17. * @date 2022-11-02
  18. */
  19. @RestController
  20. @RequestMapping(value = "/active")
  21. public class SendController {
  22.     //也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装
  23.     @Autowired
  24.     private JmsMessagingTemplate jmsMessagingTemplate;
  25.     /**
  26.      * 发送消息接口
  27.      * 发送queue消息 :http://127.0.0.1:8080/active/send?msg=ceshi1234
  28.      * 发送topic 消息: http://127.0.0.1:8080/active/topic/send?msg=ceshi1234
  29.      * 发送queue消息(延迟time毫秒) :http://127.0.0.1:8080/active/send?msg=ceshi1234&time=5000
  30.      *
  31.      * @param msg  消息
  32.      * @param type url中参数,非必须
  33.      * @param time
  34.      * @return
  35.      */
  36.     @RequestMapping({"/send", "/{type}/send"})
  37.     public String send(@PathVariable(value = "type", required = false) String type, String msg, Long time) {
  38.         Destination destination = null;
  39.         if (type == null) {
  40.             type = "";
  41.         }
  42.         switch (type) {
  43.             case "topic":
  44.                 //发送广播消息
  45.                 destination = new ActiveMQTopic("active.topic");
  46.                 break;
  47.             default:
  48.                 //发送 队列消息
  49.                 destination = new ActiveMQQueue("active.queue");
  50.                 break;
  51.         }
  52.         // System.out.println("开始请求发送:"+DateUtil.getStringDate(new Date(),"yyyy-MM-dd HH:mm:ss"));
  53.         if (time != null && time > 0) {
  54.             //延迟队列,延迟time毫秒
  55.             //延迟队列需要在 <broker>标签上增加属性 schedulerSupport="true"
  56.             delaySend(destination, msg, time);
  57.         } else {
  58.             jmsMessagingTemplate.convertAndSend(destination, msg);//无序
  59.             //jmsMessagingTemplate.convertSendAndReceive();//有序
  60.         }
  61.         return "activemq消息发送成功 队列消息:" + msg;
  62.     }
  63.     /**
  64.      * 延时发送
  65.      * 说明:延迟队列需要在 <broker>标签上增加属性 schedulerSupport="true"
  66.      *
  67.      * @param destination 发送的队列
  68.      * @param data        发送的消息
  69.      * @param time        延迟时间 /毫秒
  70.      */
  71.     public <T extends Serializable> void delaySend(Destination destination, T data, Long time) {
  72.         Connection connection = null;
  73.         Session session = null;
  74.         MessageProducer producer = null;
  75.         // 获取连接工厂
  76.         ConnectionFactory connectionFactory = jmsMessagingTemplate.getConnectionFactory();
  77.         try {
  78.             // 获取连接
  79.             connection = connectionFactory.createConnection();
  80.             connection.start();
  81.             // 获取session,true开启事务,false关闭事务
  82.             session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
  83.             // 创建一个消息队列
  84.             producer = session.createProducer(destination);
  85.             producer.setDeliveryMode(JmsProperties.DeliveryMode.PERSISTENT.getValue());
  86.             ObjectMessage message = session.createObjectMessage(data);
  87.             //设置延迟时间
  88.             message.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, time);
  89.             // 发送消息
  90.             producer.send(message);
  91.             session.commit();
  92.         } catch (Exception e) {
  93.             e.printStackTrace();
  94.         } finally {
  95.             try {
  96.                 if (producer != null) {
  97.                     producer.close();
  98.                 }
  99.                 if (session != null) {
  100.                     session.close();
  101.                 }
  102.                 if (connection != null) {
  103.                     connection.close();
  104.                 }
  105.             } catch (Exception e) {
  106.                 e.printStackTrace();
  107.             }
  108.         }
  109.     }
  110. }
复制代码
4. 配置config
  1. package com.gblfy.config;
  2. import org.apache.activemq.ActiveMQConnectionFactory;
  3. import org.apache.activemq.RedeliveryPolicy;
  4. import org.apache.activemq.command.ActiveMQQueue;
  5. import org.apache.activemq.command.ActiveMQTopic;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.jms.annotation.EnableJms;
  10. import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
  11. import org.springframework.jms.config.JmsListenerContainerFactory;
  12. import javax.jms.Queue;
  13. import javax.jms.Topic;
  14. /**
  15. * 描述:
  16. * activemq 有两种模式 queue 和 topic
  17. * queue 模式是单对单,有多个消费者的情况下则是使用轮询监听
  18. * topic 模式/广播模式/发布订阅模式 是一对多,发送消息所有的消费者都能够监听到
  19. *
  20. * @author gblfy
  21. * @date 2022-11-02
  22. */
  23. @EnableJms
  24. @Configuration
  25. public class ActiveMQConfig {
  26.     //队列名
  27.     private static final String queueName = "active.queue";
  28.     //主题名
  29.     private static final String topicName = "active.topic";
  30.     @Value("${spring.activemq.user:}")
  31.     private String username;
  32.     @Value("${spring.activemq.password:}")
  33.     private String password;
  34.     @Value("${spring.activemq.broker-url:}")
  35.     private String brokerUrl;
  36.     @Bean
  37.     public Queue acQueue() {
  38.         return new ActiveMQQueue(queueName);
  39.     }
  40.     @Bean
  41.     public Topic acTopic() {
  42.         return new ActiveMQTopic(topicName);
  43.     }
  44.     @Bean
  45.     public ActiveMQConnectionFactory connectionFactory() {
  46.         return new ActiveMQConnectionFactory(username, password, brokerUrl);
  47.     }
  48.     @Bean
  49.     public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ActiveMQConnectionFactory connectionFactory) {
  50.         DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
  51.         // 关闭Session事务,手动确认与事务冲突
  52.         bean.setSessionTransacted(false);
  53.         // 设置消息的签收模式(自己签收)
  54.         /**
  55.          * AUTO_ACKNOWLEDGE = 1 :自动确认
  56.          * CLIENT_ACKNOWLEDGE = 2:客户端手动确认
  57.          * DUPS_OK_ACKNOWLEDGE = 3: 自动批量确认
  58.          * SESSION_TRANSACTED = 0:事务提交并确认
  59.          * 但是在activemq补充了一个自定义的ACK模式:
  60.          * INDIVIDUAL_ACKNOWLEDGE = 4:单条消息确认
  61.          **/
  62.         bean.setSessionAcknowledgeMode(4);
  63.         //此处设置消息重发规则,redeliveryPolicy() 中定义
  64.         connectionFactory.setRedeliveryPolicy(redeliveryPolicy());
  65.         bean.setConnectionFactory(connectionFactory);
  66.         return bean;
  67.     }
  68.     @Bean
  69.     public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ActiveMQConnectionFactory connectionFactory) {
  70.         DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
  71.         // 关闭Session事务,手动确认与事务冲突
  72.         bean.setSessionTransacted(false);
  73.         bean.setSessionAcknowledgeMode(4);
  74.         //设置为发布订阅方式, 默认情况下使用的生产消费者方式
  75.         bean.setPubSubDomain(true);
  76.         bean.setConnectionFactory(connectionFactory);
  77.         return bean;
  78.     }
  79.     /**
  80.      * 消息的重发规则配置
  81.      */
  82.     @Bean
  83.     public RedeliveryPolicy redeliveryPolicy() {
  84.         RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
  85.         // 是否在每次尝试重新发送失败后,增长这个等待时间
  86.         redeliveryPolicy.setUseExponentialBackOff(true);
  87.         // 重发次数五次, 总共六次
  88.         redeliveryPolicy.setMaximumRedeliveries(5);
  89.         // 重发时间间隔,默认为1000ms(1秒)
  90.         redeliveryPolicy.setInitialRedeliveryDelay(1000);
  91.         // 重发时长递增的时间倍数2
  92.         redeliveryPolicy.setBackOffMultiplier(2);
  93.         // 是否避免消息碰撞
  94.         redeliveryPolicy.setUseCollisionAvoidance(false);
  95.         // 设置重发最大拖延时间-1表示无延迟限制
  96.         redeliveryPolicy.setMaximumRedeliveryDelay(-1);
  97.         return redeliveryPolicy;
  98.     }
  99. }
复制代码
5. queue消费者
  1. package com.gblfy.listener;
  2. import org.apache.activemq.command.ActiveMQMessage;
  3. import org.springframework.jms.annotation.JmsListener;
  4. import org.springframework.stereotype.Component;
  5. import javax.jms.JMSException;
  6. import javax.jms.Session;
  7. /**
  8. * TODO
  9. *
  10. * @author gblfy
  11. * @Date 2022-11-02
  12. **/
  13. @Component
  14. public class QueueListener {
  15.     /**
  16.      * queue 模式 单对单,两个消费者监听同一个队列则通过轮询接收消息
  17.      * containerFactory属性的值关联config类中的声明
  18.      *
  19.      * @param msg
  20.      */
  21.     @JmsListener(destination = "active.queue", containerFactory = "jmsListenerContainerQueue")
  22.     public void queueListener(ActiveMQMessage message, Session session, String msg) throws JMSException {
  23.         try {
  24.             System.out.println("active queue 接收到消息 " + msg);
  25.             //手动签收
  26.             message.acknowledge();
  27.         } catch (Exception e) {
  28.             //重新发送
  29.             session.recover();
  30.         }
  31.     }
  32. }
复制代码
6. topic消费者
  1. package com.gblfy.listener;
  2. import org.apache.activemq.command.ActiveMQMessage;
  3. import org.springframework.jms.annotation.JmsListener;
  4. import org.springframework.stereotype.Component;
  5. import javax.jms.JMSException;
  6. import javax.jms.Session;
  7. /**
  8. * TODO
  9. *
  10. * @author gblfy
  11. * @Date 2022-11-02
  12. **/
  13. @Component
  14. public class TopicListener {
  15.     /**
  16.      * topic 模式/广播模式/发布订阅模式 一对多,多个消费者可同时接收到消息
  17.      * topic 模式无死信队列,死信队列是queue模式
  18.      * containerFactory属性的值关联config类中的声明
  19.      *
  20.      * @param msg
  21.      */
  22.     @JmsListener(destination = "active.topic", containerFactory = "jmsListenerContainerTopic")
  23.     public void topicListener(ActiveMQMessage message, Session session, String msg) throws JMSException {
  24.         try {
  25.             // System.out.println("接收到消息:" + DateUtil.getStringDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
  26.             System.out.println("active topic 接收到消息 " + msg);
  27.             System.out.println("");
  28.             //手动签收
  29.             message.acknowledge();
  30.         } catch (Exception e) {
  31.             //重新发送
  32.             session.recover();
  33.         }
  34.     }
  35.     @JmsListener(destination = "active.topic", containerFactory = "jmsListenerContainerTopic")
  36.     public void topicListener2(ActiveMQMessage message, Session session, String msg) throws JMSException {
  37.         try {
  38.             // System.out.println("接收到消息:" + DateUtil.getStringDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
  39.             System.out.println("active topic2 接收到消息 " + msg);
  40.             System.out.println("");
  41.             //手动签收
  42.             message.acknowledge();
  43.         } catch (Exception e) {
  44.             //重新发送
  45.             session.recover();
  46.         }
  47.     }
  48. }
复制代码
6. ActiveMQ 消息存储规则

QUEUE 点对点:
特点:消息遵循先到先得,消息只能被一个消费者消费。
消息存储规则:消费者消费消息成功,MQ服务端消息删除
TOPIC订阅模式: 消息属于广播(订阅)模式,消息会被所有的topic消费者消费消息。
消息存储规则:所有消费者消费成功,MQ服务端消息删除,有一个消息没有没有消费完成,消息也会存储在MQ服务端。
举例:
已经处于运行topic消费者5个,5个消费者消费完成后,MQ服务端消息删除。
扩展点补充:如果想额外添加topic消费者,如果MQ服务端消息没有被消费完毕,新增topic消费者可以消费以前未被消费的消息,
正常新增的只会消费新的topic消息。

总结

到此这篇关于SpringBoot整合ActiveMQ的文章就介绍到这了,更多相关SpringBoot整合ActiveMQ内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行