springboot-JMS消息服务-ActiveMQ

一、ActiveMQ

  1. 介绍
    Apache ActiveMQ是Apache软件基金会所研发的开放源代码消息中间件;由于ActiveMQ是一个纯Java程序,因此只需要操作系统支持Java虚拟机,ActiveMQ便可执行。

    下载地址:http://activemq.apache.org/activemq-5153-release.html
    官方教程:http://activemq.apache.org/getting-started.html
    
  2. 网页地址与queue目录介绍
    浏览器输入:http://127.0.0.1:8161/admin/ 用户名与密码:admin

    queue目录介绍:
    Name:队列名称。
    Number Of Pending Messages:等待消费的消息个数。
    Number Of Consumers:当前连接的消费者数目
    Messages Enqueued:进入队列的消息总个数,包括出队列的和待消费的,这个数量只增不减。
    Messages Dequeued:已经消费的消息数量。

  3. ActiveMQ之点对点操作
    官方参考网址 :目录:4.13.1
    a、引入依赖:

    <!-- 整合消息队列ActiveMQ -->
    <dependency>
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>  
    <!-- 若配置线程池则加入 -->
    <dependency>
    <groupId>org.messaginghub</groupId>
    <artifactId>pooled-jms</artifactId>
    </dependency>
    

    b、application.properties配置文件

    #整合jms测试,安装在别的机器,防火墙和端口号记得开放,若防火墙已关闭,此处可忽略
    spring.activemq.broker-url=tcp://127.0.0.1:61616
    #集群配置
    #spring.activemq.broker-url=failover:(tcp://localhost:61616,tcp://localhost:61617)
    spring.activemq.user=admin
    spring.activemq.password=admin
    #使用连接池
    spring.activemq.pool.enabled=true
    #连接池最大连接数
    spring.activemq.pool.max-connections=100
    

    c、在启动类加注解

    @SpringBootApplication
    @EnableJms    //开启支持jms
    public class Springboot07Application {
    
        @Bean
        /**
         * 将当前方法注入到spring,拿到一个Queue对象
         * @Component 将整个类注入到spring产生一个bean对象
         * @Bean 是将当前方法注入到spring,把当前方法返回的对象作为-个bean对象使用
         */
        public Queue queue(){
            return new ActiveMQQueue("test.queue");
        }
    }
    

    d、提供一个发送消息的服务 ----- 写一个service层

    //发送消息的服务,也叫做消息生产者
    public interface ActiveService {
    
        /**
         *
         * @param destination    //指定接收消息的对列名
         * @param msg             //发送的消息
         */
        public void sendMsg(Destination destination,String msg);
    
        /**
         * 使用默认消息队列
         * @param msg
         */
        public void defaultSendMsg(String msg);
    }
    
    

    e、实现接口
    通过JmsMessgingTemplate发送消息

    @Service
    public class ActiveServiceImpl implements ActiveService {
    
        @Autowired
        private Queue queue;   //队列对象
    
        @Autowired
        private JmsMessagingTemplate template; //消息队列模板 ,类似于jdbcTemplate模板
    
        @Override
        public void sendMsg(Destination destination, String msg) {
            //将消息发送到指定消息队列destination
            template.convertAndSend(destination,msg);
        }
    
        @Override
        public void defaultSendMsg(String msg) {
            //将消息发送到默认消息队列
            template.convertAndSend(msg);
        }
    }
    

    f、从controller层接收消息
    这里使用了JsonData工具类,返回json数据

    @RestController
    @RequestMapping("/mq")
    public class ActiveController {
    
        @Autowired
        private ActiveService activeService;
    
        @RequestMapping("/active")
        //这是前台发过来的消息
        public Object active(String msg){
            Destination destination = new ActiveMQQueue("test.queue");//指定接收队列
            activeService.sendMsg(destination,msg);
            return JsonData.buildSuccess();
        }
    }
    

    g、在jsm文件夹中创建消息消费者,消费掉刚才发送的消息

    @Component
    public class ActiveConsumer {
    
        /**
         * 监听活动中的消息,并消费  --这是实时监听
         * @JmsListener 消息监听(实时监听,只有发现有消息发送过来,会立刻消费
         * @param msg
         */
        @JmsListener(destination = "test.queue")  //指定接收队列
        public void consumeMsg(String msg){
            System.out.println("ActiveConsume收到的报文是:" + msg);
        }
    }
    

    h、测试

  4. ActiveMQ之发布订阅模式
    订阅模式,一个消息可以被多个消费者消费,这是和点对点模式的最大区别。同时也支持点对点和发布订阅同时使用。

    a、在配置文件配置

    #开启订阅模式,默认是点对点模式
    spring.jms.pub-sub-domain=true
    

    b、启动类同样需要@EnableJms ,然后加入一个topic 主题对象

    	/**
         * 订阅者模式  --发布者
         * @return
         */
        @Bean
        public Topic topic(){
            return new ActiveMQTopic("test.topic");//指定接收队列
        }
    

    c、业务层提供生产者(也就是消息发布者)

    	/**
         * 订阅者模式:消息发布者
         * @param msg
         */
        public void  producer(String msg);
    

    d、实现业务层

    @Autowired
        private Topic topic;
    
        @Override
        public void producer(String msg) {
            template.convertAndSend(topic,msg);
        }
    

    e、创建消费者

    @Component
    public class TopicConsumer {
    
        /**
         * 订阅模式消费者
         * @param msg
         */
        @JmsListener(destination = "test.topic") //指定接收队列
        public void consumer1(String msg){
            System.out.println("消费者1报文:" + msg);
        }
    
        @JmsListener(destination = "test.topic")
        public void consumer2(String msg){
            System.out.println("消费者2报文:" + msg);
        }
    
        @JmsListener(destination = "test.topic")
        public void consumer3(String msg){
            System.out.println("消费者3报文:" + msg);
        }
    }
    

    f、在controller层编写代码

    	/**
         * 订阅者模式   --消息生产
         * @param msg
         * @return
         */
        @RequestMapping("/topic")
        public Object topic(String msg){
            activeService.producer(msg);
            return JsonData.buildSuccess();
        }
    

    g、测试

  5. 同时支持点对点和订阅者模式

    a、修改配置文件,把spring.jms.pub-sub-domain=true 注释
    b、在启动类添加代码

     /**
     * 同时支持点对点和订阅者模式
     * @param activeMQConnectionFactory
     * @return
     */
    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ConnectionFactory activeMQConnectionFactory) {
        DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
        bean.setPubSubDomain(true);
        bean.setConnectionFactory(activeMQConnectionFactory);
        return bean;
    }
    

    c、修改订阅者注解
    在原订阅者模式注解 @JmsListener 追加 containerFactory="jmsListenerContainerTopic"

    @Component
    public class TopicConsumer {
    
        /**
         * 订阅模式消费者
         * @param msg
         */
        @JmsListener(destination = "test.topic",containerFactory="jmsListenerContainerTopic")
        public void consumer1(String msg){
            System.out.println("消费者1报文:" + msg);
        }
    
        @JmsListener(destination = "test.topic",containerFactory="jmsListenerContainerTopic")
        public void consumer2(String msg){
            System.out.println("消费者2报文:" + msg);
        }
    
        @JmsListener(destination = "test.topic",containerFactory="jmsListenerContainerTopic")
        public void consumer3(String msg){
            System.out.println("消费者3报文:" + msg);
        }
    }
    

    d、测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中使用MQTT发送消息ActiveMQ,可以按照以下步骤进行代码编写: 1. 首先,确保你的Spring Boot项目中已经引入了`spring-boot-starter-activemq`依赖。这个依赖会自动集成并配置ActiveMQ。 2. 创建一个MQTT发送消息的业务类,可以命名为`MqttMessageSender`。在这个类中,注入`JmsTemplate`来实现消息的发送。示例代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Component; @Component public class MqttMessageSender { @Autowired private JmsTemplate jmsTemplate; public void sendMessage(String destination, String message) { jmsTemplate.convertAndSend(destination, message); } } ``` 3. 在你的控制器或其他需要发送消息的地方,注入`MqttMessageSender`,并调用`sendMessage`方法发送消息。示例代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class MessageController { @Autowired private MqttMessageSender messageSender; @PostMapping("/send-message") public String sendMessage(@RequestBody String message) { messageSender.sendMessage("queue.destination", message); return "Message sent successfully"; } } ``` 在这个例子中,我们创建了一个POST接口`/send-message`,用来接收请求体中的消息,并调用`MqttMessageSender`发送消息到名为`queue.destination`的目的地。 请根据你的实际需求进行进一步的配置和适配。通过以上步骤,你可以在Spring Boot中编写代码来实现将MQTT消息发送到ActiveMQ。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot+ActiveMq+MQTT实现消息的发送和接收](https://download.csdn.net/download/yangyi30/10786299)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [activemq中怎么知道推送消息是否成功_SpringBoot集成ActiveMQ实例详解](https://blog.csdn.net/weixin_39589644/article/details/110219743)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值