springBoot集成ActiveMQ

ActiveMQ作为比较强大的消息中间件有点这里就不在赘述了,主要讲述趟路的过程。

在Spring Boot的starter中专门集成了ActiveMQ,因此,本篇文章我们就来讲讲对ActiveMQ的集成。

JMS规范

JMS即Java消息服务(Java Message Service)应用程序接口,是一个Java平台中关于面向消息中间件(MOM)的API,用于在两个应用程序之间,或分布式系统中发送消息,进行异步通信。Java消息服务是一个与具体平台无关的API,绝大多数MOM提供商都对JMS提供支持。

JMS的消息机制有2种模型,一种是队列的形式(Point to Point—)发送的消息只能被一个消费者消费;一种是订阅(Topic)模式,可以被多个订阅者订阅,订阅者都会接收到同样的消息。

而ActiveMQ就是对JMS的实现之一。

ActiveMQ的两种消息传递类型:

(1)点对点传输,即一个生产者对应一个消费者,生产者向broke推送数据,数据存储在broke的一个队列中,当消费者接受该条队列里的数据。

(2)基于发布/订阅模式的传输,即根据订阅话题来接收相应数据,一个生产者可向多个消费者推送数据,与MQTT协议的实现是类似的。

Spring Boot集成ActiveMQ

1.引入依赖

在pom文件中引入ActiveMQ的依赖

<!--ActiveMQ依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-activemq</artifactId>
        </dependency>

此时如果不需要web或其他相关处理,只引入该依赖即可。如果使用pool的话, 就需要在pom中加入以下依赖:

<dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-pool</artifactId>
        </dependency>

2.配置yml

在系统配置文件中添加activeMQ的配置信息

复制代码
# activeMq 配置
  activemq:
    broker-url: tcp://192.168.12.226:61616
    user: admin
    password: admin
    pool:
      # 使用flase,此处改为true报错,不清楚什么原因
      enabled: false
      max-connections: 50
  jms:
    listener:
      #同时消费数
      concurrency: 3
      #最大消费数
      max-concurrency: 3
    pub-sub-domain: false #配置消息的类型,如果是true则表示为topic消息,如果为false表示Queue消息
复制代码

3.修改启动类,添加@EnableJms注解

复制代码
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jms.annotation.EnableJms;


@SpringBootApplication
@MapperScan({"com.ckfuture.pro.*.*.dao"})
@EnableJms  //启动消息队列
public class ApiserverApplication {
    private static final Logger logger = LoggerFactory.getLogger(ApiserverApplication.class);
    public static void main(String[] args) {
        SpringApplication.run(ApiserverApplication.class, args);
        logger.info("------------ API Service Start Running--------------");
    }
}
复制代码

4.添加activeMQ配置

复制代码
package com.ckfuture.pro.config;



import org.apache.activemq.command.ActiveMQQueue;

import org.apache.activemq.command.ActiveMQTopic;
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.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;

/**
 * @descrption: activeMQ配置类
 * @author: CKFuture
 * @since: 2021-09-29 10:12
 * @version: v1.0
 * @LastEditTime:
 * @LastEditors:
 * @copyright: hrbckfuture.com
 */
@Configuration
public class MyMqConfig {
    /**
     * 队列模式
     * @return
     */
    @Bean
    public Queue queue() {
        return new ActiveMQQueue("sms.queue");
    }

    /**
     * 广播模式
     * @return
     */
    @Bean
    public Topic topic() {
        return new ActiveMQTopic("sms.topic");
    }

    /**
     * 发布-订阅模式的ListenerContainer
     */
    @Bean
    public JmsListenerContainerFactory<?> topicListenerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setPubSubDomain(true);
        factory.setConnectionFactory(connectionFactory);
        return factory;
    }
    /**
     * P2P模式的ListenerContainer
     */
    @Bean
    public JmsListenerContainerFactory<?> queueListenerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setPubSubDomain(false);
        factory.setConnectionFactory(connectionFactory);
        return factory;
    }


}
复制代码

activeMQ 默认实现队列消息,通过yml中的设置 :

 pub-sub-domain: true #配置消息的类型,如果是true则表示为topic消息,如果为false表示Queue消息
可以实现订阅模式。但实际生成过程中是既需要队列模式又需要订阅模式,所以要添加两个ListenerContainer。

5.编写生产者

复制代码
package com.ckfuture.pro.activeMQ;

import com.ckfuture.pro.config.MyMqConfig;
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.jms.Queue;
import javax.jms.Topic;

/**
 * @descrption: 消息中间件 点对点 生产者
 * @author: CKFuture
 * @since: 2021-09-29 11:16
 * @version: v1.0
 * @LastEditTime:
 * @LastEditors:
 * @copyright: hrbckfuture.com
 */
@Component
public class Producer {
    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;
    /**
     * 队列
     */
    @Resource
    private Queue queue;
    public void sendMsg(String msg) {
        System.out.println("发送消息内容 :" + msg);
        this.jmsMessagingTemplate.convertAndSend(this.queue, msg);
    }

    /**
     * 广播
     */
    @Resource
    private Topic topic;
    public void sendTopic(String msg) {
        System.out.println("发送Topic消息内容 :"+msg);
        this.jmsMessagingTemplate.convertAndSend(this.topic, msg);
    }

}
复制代码

6.编写消费者

复制代码

package com.ckfuture.pro.activeMQ;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
/**
* @descrption: 消息中间件 点对点 消费者
* @author: CKFuture
* @since: 2021-09-29 11:16
* @version: v1.0
* @LastEditTime:
* @LastEditors:
* @copyright: hrbckfuture.com
*/
@Component
public class Consumer {
@JmsListener(destination = "sms.queue", containerFactory = "queueListenerFactory")
public void receiveMsg(String text) {
System.out.println("接收到消息 : "+text);
}

@JmsListener(destination = "sms.topic", containerFactory = "topicListenerFactory")
public void receiveTopic1(String text) {
System.out.println("receiveTopic1接收到Topic消息 : " + text);
}

@JmsListener(destination = "sms.topic", containerFactory = "topicListenerFactory")
public void receiveTopic2(String text) {
System.out.println("receiveTopic2接收到Topic消息 : " + text);
}

}
复制代码

7.编写测试类

复制代码
package com.ckfuture.pro;

import com.ckfuture.pro.activeMQ.Producer;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
public class ActiveMqTests {
    @Autowired
    private Producer producer;
    @Test
    public void sendSimpleQueueMessage() {
        this.producer.sendMsg("提现200.00元");
    }
    @Test
    public void sendSimpleTopicMessage() {
        this.producer.sendTopic("提现200.00元");
    }
}
复制代码

队列测试结果:

 

 

订阅测试结果:

 

posted @   创客未来  阅读(853)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示