activeMq在springboot项目中集成和使用

1. 环境准备

首先,需要下载并启动 ActiveMQ 服务。ActiveMQ 是开箱即用的。

  1. 下载与解压 :访问 ActiveMQ 官网 下载最新版本(如 apache-activemq-5.16.3),解压到本地目录-1-9

  2. 启动服务

    • Windows : 进入 bin/win64 目录,双击运行 activemq.bat

    • Mac/Linux : 在终端进入 bin 目录,执行 ./activemq start

  3. 验证启动 :打开浏览器访问 http://127.0.0.1:8161/admin/,默认用户名和密码均为 admin。看到管理界面说明服务启动成功-1-9

🔧 2. Spring Boot 项目配置

2.1 添加依赖

在项目的 pom.xml 文件中引入 Spring Boot 的 ActiveMQ Starter 包,它会自动引入 JMS 相关依赖和 ActiveMQ 客户端

复制代码
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>
    <!-- 如果需要使用连接池,还需引入下面这个依赖 -->
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-pool</artifactId>
    </dependency>
</dependencies>
2.2 配置文件 (application.yml)

application.yml 中配置 ActiveMQ 的服务地址和连接信息-1-3-7

yaml

复制代码
spring:
  activemq:
    broker-url: tcp://localhost:61616   # ActiveMQ 默认连接地址
    user: admin                          # 登录用户名
    password: admin                      # 登录密码
    # 是否启用连接池(需要 activemq-pool 依赖)
    pool:
      enabled: true
      max-connections: 10                # 最大连接数
  # JMS 配置
  jms:
    # false: 点对点模式(Queue) | true: 发布/订阅模式(Topic)
    # 注意:如果同时需要支持两种模式,可以在消费者中单独指定,不建议全局修改
    pub-sub-domain: false

💻 3. 代码实现

3.1 定义目的地 (Queue / Topic)

推荐使用 Java 配置类来创建队列(Queue)和主题(Topic),以便在后续代码中按名称注入使用-1-9

复制代码
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 javax.jms.Queue;
import javax.jms.Topic;

@Configuration
public class ActiveMQConfig {

    @Bean
    public Queue queue() {
        return new ActiveMQQueue("my-queue");
    }

    @Bean
    public Topic topic() {
        return new ActiveMQTopic("my-topic");
    }
}
3.2 消息生产者

使用 Spring 提供的 JmsTemplate 来发送消息,非常简洁-3-7-9

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import javax.jms.Queue;
import javax.jms.Topic;

@Service
public class ProducerService {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private Queue queue;   // 注入队列

    @Autowired
    private Topic topic;   // 注入主题

    // 发送 Queue 消息
    public void sendQueueMessage(String message) {
        jmsTemplate.convertAndSend(queue, message);
        System.out.println("已发送 Queue 消息: " + message);
    }

    // 发送 Topic 消息
    public void sendTopicMessage(String message) {
        jmsTemplate.convertAndSend(topic, message);
        System.out.println("已发送 Topic 消息: " + message);
    }
}
3.3 消息消费者

使用 @JmsListener 注解来监听指定的目的地。当有消息到达时,被注解的方法会自动执行-1-3-7

复制代码
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
public class ConsumerService {

    // 监听队列 "my-queue"
    @JmsListener(destination = "my-queue")
    public void receiveQueueMessage(String message) {
        System.out.println("Queue消费者收到消息: " + message);
        // 在这里执行具体的业务逻辑
    }

    // 监听主题 "my-topic"
    // 注意:如果配置文件 spring.jms.pub-sub-domain 未设置为 true,
    // 则必须显式指定 containerFactory 来支持主题模式
    @JmsListener(destination = "my-topic", containerFactory = "jmsListenerContainerFactory")
    public void receiveTopicMessage(String message) {
        System.out.println("Topic消费者收到消息: " + message);
    }
}

⚙️ 4. 高级配置与注意事项

4.1 同时支持 Queue 和 Topic

Spring Boot 默认配置是点对点模式。如果项目中需要同时支持 Queue(点对点)和 Topic(发布/订阅),不能仅靠 spring.jms.pub-sub-domain 全局配置,因为它会强制将所有 @JmsListener 视为同一种模式-1

解决方案 :为 Topic 单独配置一个 JmsListenerContainerFactory-1

ActiveMQConfig 配置类中添加如下 Bean:

复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import javax.jms.ConnectionFactory;

@Configuration
public class ActiveMQConfig {
    // ... 之前的 queue 和 topic 定义

    @Bean
    public JmsListenerContainerFactory<?> jmsListenerContainerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        // 设置为 true,表示这个工厂生成的是主题模式的监听器
        factory.setPubSubDomain(true);
        return factory;
    }
}

然后在消费 Topic 的 @JmsListener 中,通过 containerFactory 属性引用这个 Bean 即可(如 3.3 节所示)-1

4.2 消息持久化

为了确保消息不会因为 Broker 宕机而丢失,应开启消息持久化-3-7。发送消息时可以进行设置:

复制代码
// 使用 JmsTemplate 发送持久化消息
jmsTemplate.convertAndSend(queue, message, messagePostProcessor -> {
    messagePostProcessor.setJMSDeliveryMode(DeliveryMode.PERSISTENT);
    return messagePostProcessor;
});

如果使用的是 ActiveMQ XML 配置文件,也需要确保持久化适配器(如 KahaDB)配置正确-4

✅ 5. 测试

你可以编写一个简单的 Controller 或测试类来调用生产者,验证整个流程-1

复制代码
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private ProducerService producerService;

    @GetMapping("/sendQueue")
    public String sendQueue() {
        producerService.sendQueueMessage("Hello ActiveMQ Queue!");
        return "Queue 消息已发送";
    }
}

启动 Spring Boot 应用,访问对应的接口,观察控制台是否打印出消费者接收到的消息日志。

相关推荐
宠友信息23 分钟前
消息序号如何保证即时通讯源码聊天记录稳定加载
java·spring boot·redis·python·mysql·uni-app
豆瓣鸡3 小时前
XXL-JOB 定时任务——从 Docker 部署到分片广播,分布式任务调度落地
spring boot·分布式·docker·定时任务
宠友信息6 小时前
MySQL复合索引与Druid优化仿小红书源码个人主页查询链路
数据库·spring boot·websocket·mysql·uni-app
hdsoft_huge9 小时前
SpringBoot系列18:SpringSecurity登录鉴权,JWT无状态Token认证完整流程(生产级落地)
java·spring boot·后端
万亿少女的梦16811 小时前
基于微信小程序、Spring Boot与Vue3的智慧养老管理系统设计与实现
spring boot·redis·微信小程序·mybatis·vue3
L-影12 小时前
springboot启动流程
java·spring boot·spring
我是唐青枫14 小时前
Java Neo4j 实战指南:从图模型、Cypher 到 Spring Boot 关系查询
java·spring boot·neo4j
Komore31514 小时前
Spring Boot框架下的一个简单的接口开发
java·spring boot·后端
大阳光男孩1 天前
Spring Boot 整合 Debezium 实现 MySQL 增量数据监听(嵌入式版)
spring boot·后端·mysql
X-⃢_⃢-X1 天前
一、第一阶段:认识 Spring Boot
java·spring boot·后端