SpringBoot 在使用Activemq过程中消息间隔性丢失问题

在上手Activemq时遇到了奇怪的问题,消息会间隔性的出现搜不到的情况,因为偶尔出现一两次可能是网络不稳定的问题,一直出现就肯定是哪里出了问题

找了一些资料,因为ActiveMq有两种消息模型,一种是Queue(点对点模式),一种是Topic(发布订阅模式),简单描述下这两种模式的区别

  • Queue: 点对点,一对一模式,该模式下的消息会确保被某一个消费者接收,就是说存在很多消费者的话,只有其中一个会接受到消息,如果当前没有消费者的话,消息会被保存下来,当有对应的消费者连接上时,就把该消息推送给这位新的消费者。
  • Topic:订阅模式,这种模式的消息可以被多个消费者同时接收(如果有消费者的话),如果当时没有消费者,那么这条消息就会被丢弃,不会进行保存,后面即使有新的消费者,也接收不到该消息了

可以发现,上面描述的问题其实就是消息在点对点模式下的特征,所以要解决的话就只需要将消息的推送模式改为发布订阅模式就好了

消息生产者:

    ActiveMQTopic topic = new ActiveMQTopic(destination);
    jmsMessagingTemplate.convertAndSend(topic, data);

ActiveMQTopic类:订阅模式
ActiveMQQueue类:点对点模式

消息消费方:

需要在application.properties中配置消息接收模式(默认是Point)

spring.jms.pub-sub-domain=true
可以使用以下步骤在Spring Boot项目集成ActiveMQ: 1. 在pom.xml添加ActiveMQ依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> ``` 2. 在application.properties文件添加ActiveMQ配置: ```properties spring.activemq.broker-url=tcp://localhost:61616 spring.activemq.user=admin spring.activemq.password=admin ``` 3. 创建一个消息生产者: ```java import javax.jms.ConnectionFactory; import javax.jms.Queue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.core.JmsMessagingTemplate; import org.springframework.stereotype.Component; @Component public class MessageProducer { @Autowired private JmsMessagingTemplate jmsMessagingTemplate; @Autowired private Queue queue; public void send(String message) { this.jmsMessagingTemplate.convertAndSend(queue, message); } } ``` 4. 创建一个消息消费者: ```java import javax.jms.Queue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jms.annotation.JmsListener; import org.springframework.stereotype.Component; @Component public class MessageConsumer { @Autowired private Queue queue; @JmsListener(destination = "${spring.activemq.queue-name}") public void receive(String message) { System.out.println("Received message: " + message); } } ``` 5. 在应用程序使用消息生产者发送消息: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class MyApp implements CommandLineRunner { @Autowired private MessageProducer messageProducer; @Override public void run(String... args) throws Exception { messageProducer.send("Hello, World!"); } } ``` 这样就可以在你的Spring Boot应用程序使用ActiveMQ了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值