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 应用,访问对应的接口,观察控制台是否打印出消费者接收到的消息日志。

相关推荐
花千树-01020 小时前
兼容 ThreadLocal 的用户上下文透传方案:WebFlux 项目改造实践
java·spring boot·servlet·jetty
s1mple“”1 天前
大厂Java面试实录:从Spring Boot到AI技术的电商场景深度解析
spring boot·redis·微服务·kafka·向量数据库·java面试·ai技术
yhole1 天前
springboot三层架构详细讲解
spring boot·后端·架构
golang学习记1 天前
IDEA 2026.1全新调试新特性:Spring Boot调试不再靠猜!
java·spring boot·intellij-idea
橘子编程1 天前
OpenClaw(小龙虾)完整知识汇总
java·前端·spring boot·spring·spring cloud·html5
大阿明1 天前
SpringBoot - Cookie & Session 用户登录及登录状态保持功能实现
java·spring boot·后端
Binary-Jeff1 天前
Spring 创建 Bean 的关键流程
java·开发语言·前端·spring boot·后端·spring·学习方法
TlYf NTLE1 天前
Spring Boot3.3.X整合Mybatis-Plus
spring boot·后端·mybatis
SHoM SSER1 天前
Spring Boot性能提升的核武器,速度提升500%!
java·spring boot·后端
weixin_425023001 天前
Spring Boot 2.7 + JDK8 集成 Knife4j 4.1.0 教程(仅展示带注解接口)
java·spring boot·后端