Spring BootJMS ActiveMQ

xiaoxiao2021-02-28  29

ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线。ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provider实现,尽管JMS规范出台已经是很久的事情了,但是JMS在当今的J2EE应用中间仍然扮演着特殊的地位。

if (如果不想安装ActiveQM) {

    可尝试使用内存代理;

    Ctrl + F 输入: 使用内存代理

} else {

首先去http://activemq.apache.org/download.html 下载最新版本5.15.3release, 解压apache-activemq-5.15.3-bin.zip(或者apache-activemq-5.15.3-bin.tar.gz)目录如下:

启动activeqm.bat

小提示:

⒈ 这个仅仅是最基础的ActiveMQ的配置,很多地方都没有配置因此不要直接使用这个配置用于生产系统 ⒉ 有的时候由于端口被占用,导致ActiveMQ错误,ActiveMQ可能需要以下端口 1099(JMX),61616 (默认的TransportConnector) ⒊ 如果没有物理网卡,或者MS的LoopBackAdpater Multicast会报一个错误

打开浏览器登录http://localhost:8161

pom.xml 添加依赖:

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

application.properties 文件配置:

# 消息队列 spring.activemq.broker-url=tcp://localhost:61616 # 上述小提示部分 spring.activemq.user=admin spring.activemq.password=admin

使用内存代理

生产者:

@Service("producer") public class Producer { @Autowired // 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装 private JmsMessagingTemplate jmsTemplate; // 发送消息,destination是发送到的队列,message是待发送的消息 public void sendMessage(Destination destination, final String message){ jmsTemplate.convertAndSend(destination, message); } }

消费者:

@Component public class Consumer { // 使用JmsListener配置消费者监听的队列,其中text是接收到的消息 @JmsListener(destination = "myDestination.queue") // 目的地 public void receiveQueue(String text) { System.out.println("Consumer收到的报文为:"+text); } }

测试:

@Autowired private Producer producer; @Test public void myActiveMQ() { Destination destination = new ActiveMQQueue("myDestination.queue"); // 目的地 producer.sendMessage(destination , "hello , ActiveMQ"); }

在使用JmsTemplate进行消息发送的时候,我们需要知道消息发送的目的地,即destination。在Jms中有一个用来表示目的地的Destination接口,它里面没有任何方法定义,只是用来做一个标识而已。当我们在使用JmsTemplate进行消息发送时没有指定destination的时候将使用默认的Destination。默认Destination可以通过在定义jmsTemplate bean对象时通过属性defaultDestinationdefaultDestinationName来进行注入,defaultDestinationName对应的就是一个普通字符串。在ActiveMQ中实现了两种类型的Destination,一个是点对点的ActiveMQQueue,另一个就是支持订阅/发布模式的ActiveMQTopic。在定义这两种类型的Destination时我们都可以通过一个name属性来进行构造。

转载请注明原文地址: https://www.6miu.com/read-2623795.html

最新回复(0)