ActiveMQ 实战 - SpringBoot整合ActiveMQ

Spring Boot整合ActiveMQ的主要步骤如下:

1. 添加依赖

pom.xml文件中添加ActiveMQ客户端的依赖。这里以较新的Spring Boot和ActiveMQ版本为例(请根据实际需要替换为最新版本):

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>
</dependencies>

2. 配置连接信息

application.propertiesapplication.yml配置文件中设置ActiveMQ Broker的连接参数,例如:

# application.properties
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=password

或者

# application.yml
spring:
  activemq:
    broker-url: tcp://localhost:61616
    user: admin
    password: password

3. 创建消息生产者和消费者

  • 创建生产者:通过@Autowired注入JmsTemplate对象,并使用其convertAndSend()方法发送消息到队列或主题。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import javax.jms.Queue; // 如果是Queue模式
// 或 import javax.jms.Topic; // 如果是Topic模式

@Component
public class MyProducer {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private Queue myQueue; // 或 @Autowired private Topic myTopic;

    public void sendMessage(String message) {
        jmsTemplate.convertAndSend(myQueue, message); // 或 jmsTemplate.convertAndSend(myTopic, message);
    }
}
  • 创建消费者:实现MessageListener接口或者使用@JmsListener注解来监听指定队列或主题的消息。
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

@Component
public class MyConsumer implements MessageListener {

    @Override
    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            try {
                String receivedMessage = ((TextMessage) message).getText();
                System.out.println("Received message: " + receivedMessage);
                // 在此处处理接收到的消息
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    }
}

// 或者使用@JmsListener注解的方式

import org.springframework.jms.annotation.JmsListener;

@Component
public class AnotherConsumer {

    @JmsListener(destination = "myQueue") // 或 @JmsListener(destination = "myTopic")
    public void processMessage(String message) {
        System.out.println("Received message: " + message);
        // 在此处处理接收到的消息
    }
}

4. 持久订阅与非持久订阅

对于发布/订阅模型中的持久订阅,可以使用@JmsListener时加入subscriptionDurability属性:

@JmsListener(destination = "myTopic", subscription = "durableSubscription", subscriptionDurability = "Durable")

以上是一个基本的Spring Boot整合ActiveMQ的实战示例,实际应用中可能还需要根据具体业务需求进行更详细的配置和消息处理逻辑编写。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值