在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);
}
}
}
运行结果
说明
原文链接: