<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
在application.properties中配置Active MQ:
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false
#默认值false,表示点到点模式,true时代表发布订阅模式
spring.jms.pub-sub-domain=false
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import javax.jms.Destination;
@Service("producer")
public class Producer {
/**
* 也可以注入JmsTemplate,JmsMessagingTemplate对JmsTemplate进行了封装
*/
@Autowired
private JmsMessagingTemplate jmsTemplate;
/**
* 发送消息,destination是发送到的队列,message是待发送的消息
*
* @param destination
* @param message
*/
public void sendMessage(Destination destination, final String message) {
jmsTemplate.convertAndSend(destination, message);
}
}
新增消息消费者:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class ConsumerListener {
private static Logger logger = LoggerFactory.getLogger(Consumer.class);
/**
* 使用JmsListener配置消费者监听的队列
* @param receivedMsg 接收到的消息
*/
@JmsListener(destination = "myDest.queue")
public void receiveQueue(String receivedMsg) {
logger.info("Consumer收到的报文为: {}", receivedMsg);
}
}
消费者2 ConsumerListener2 的代码同上,但是日志如下:
logger.info("Consumer2收到的报文为: {}", receivedMsg);
温馨提示,消息消费者和生产者的类上必须加上注解 @Component 或者 @Service,使得消息消费者类就会被委派给Listener类,原理类似于使用SessionAwareMessageListener以及MessageListenerAdapter来实现消息驱动POJO。
import org.apache.activemq.command.ActiveMQQueue;
import javax.jms.Destination;
@Autowired
private Producer producer;
@Test
public void jmsActiveMqTest() throws InterruptedException {
Destination destination = new ActiveMQQueue("myDest.queue");
for (int i = 0; i < 21; i++) {
producer.sendMessage(destination, String.format("My name is Wiener%s", i));
}
}
测试结果:
Consumer收到的报文为: My name is Wiener0
Consumer2 收到的报文为:My name is Wiener1
Consumer收到的报文为: My name is Wiener2
Consumer2 收到的报文为:My name is Wiener3
Consumer收到的报文为: My name is Wiener4
Consumer2 收到的报文为:My name is Wiener5
Consumer收到的报文为: My name is Wiener6
Consumer2 收到的报文为:My name is Wiener7
...
Spring Boot 整合 JMS(Active MQ 实现)
原文:https://www.cnblogs.com/east7/p/13127364.html