ActiveMQ学习-与spring整合,在spring-boot中使用 (5)

栏目: Java · 发布时间: 7年前

内容简介:在spring-boot中使用ActiveMQ相当的简单引入依赖添加配置文件

在spring-boot中使用ActiveMQ相当的简单

引入依赖

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

添加配置文件

spring:
  activemq:
    broker-url: tcp://localhost:61616

spring-boot里也可以进行数据连接池的配置,这个之前几篇博客已经都配置好了,这里就不做配置了

消息提供者

@Service("producer")
public class Producer {

  @Autowired
  private JmsMessagingTemplate jmsTemplate;

  // 发送消息,destination是发送到的队列,message是待发送的消息
  public void sendMessage(Destination destination, String message) {
    jmsTemplate.convertAndSend(destination, message);
  }

}

消息消费者1

@Component
public class Consumer1 {
  // 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
  @JmsListener(destination = "amq-demo")
  public void receiveQueue(String text) {
    System.out.println("Consumer1: " + text);
  }
}

消息消费者2

@Component
public class Consumer2 {
  // 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
  @JmsListener(destination = "amq-demo")
  public void receiveQueue(String text) {
    System.out.println("Consumer2: " + text);
  }
}

消息消费者3

@Component
public class Consumer3 {

  @JmsListener(destination = "amq-demo2")
  public void consumerMessage(String text) {
    System.out.println("收到来自amq-demo2队列的消息: " + text);
  }

}

test方法

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

  @Autowired
  private Producer producer;

  @Test
  public void contextLoads() {
    Destination destination = new ActiveMQQueue("amq-demo");

    for (int i = 1; i <= 5; i++) {
      producer.sendMessage(destination, "Producer消息" + i);
    }
  }

}

运行结果

ActiveMQ学习-与spring整合,在spring-boot中使用 (5)

说明

  1. 提供者发送消息到ActiveMQ服务器里
  2. 消费者1和消费者2同时消费数据,它们不会重复消费,既有一个消费者把消息消费了,其它消费者就不会再消费这条数据了
  3. 消费者2消费数据的同时还将消息重新发出(这里的意思应该是消费者2临时充当了消息提供者的角色了,这个功能可以处理一些复杂的,一个消费者处理不完的消息,或者处理一些消息后,还有后续的操作的业务)
  4. 消费者3监听消费者2发出的消息然后进行消费

注意,运行test方法进行测试前要先启动 ActiveMQ

原文链接:


以上所述就是小编给大家介绍的《ActiveMQ学习-与spring整合,在spring-boot中使用 (5)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

HTML5秘籍

HTML5秘籍

Matthew MacDonald / 李松峰、朱巍 / 人民邮电出版社 / 2012-8 / 79.00元

《HTML5秘籍》共包括四个部分,共12章。第一部分介绍了html5的发展历程,利用html5重新构造网页,以及html5的语义元素。第二部分介绍了html5对传统web表单的翻新、html5中的音频与视频、canvas绘图技术、css3等内容。第三部分介绍了数据存储、离线应用、与web服务器通信,以及html5与javascript技术的强大结合等内容。第四部分为附录,简单介绍了css和java......一起来看看 《HTML5秘籍》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试