关于安装activeMQ服务器请参考《ActiveMQ的安装和部署》。
一、新建spring boot工程,并加入依赖。如图。
二、小Demo的目录结构
三、代码
1、pom.xml(这个是创建的时候自动生成的,可以不看)
2、配置信息application.properties
# #号为注释
# MQ的配置信息start
# URL of the ActiveMQ broker. Auto-generated by default. For instance `tcp://localhost:61616`
# failover:(tcp://localhost:61616,tcp://localhost:61617)
# tcp://localhost:61616
########################################################################################
## activemq配置的例子
##spring.activemq.broker-url=failover:tcp://10.10.101.37:61616,tcp://10.10.101.38:61616,tcp://10.10.101.39:61616
##spring.activemq.user=admin
##spring.activemq.password=admin
##spring.activemq.in-memory=true
##spring.jms.pub-sub-domain=false
##spring.activemq.pool.enabled=false
##spring.activemq.queue=queue
##spring.activemq.topic=topic
########################################################################################
spring.activemq.broker-url=tcp://127.0.0.1:61616
spring.activemq.user=admin
spring.activemq.password=admin
spring.activemq.in-memory=true
spring.activemq.pool.enabled=false
# MQ的配置信息end
3、生产者
package com.example.demo.roro.activemq;
import javax.jms.Destination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
@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);
}
}
4、消费者
package com.example.demo.roro.activemq;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
@Component
public class Consumer {
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener(destination = "mytest.queue")
public void receiveQueue(String text) {
System.out.println("Consumer收到的报文为:"+text);
}
}
5、测试代码
package com.example.demo;
import javax.jms.Destination;
import org.apache.activemq.command.ActiveMQQueue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.demo.roro.activemq.Producer;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootMQdemoApplicationTests {
@Autowired
private Producer producer;
@Test
public void contextLoads() throws InterruptedException {
Destination destination = new ActiveMQQueue("mytest.queue");
for (int i = 0; i < 100; i++) {
producer.sendMessage(destination, "I am a message");
}
}
}
测试前先看一眼active控制台
四、测试。
右键测试类,Junit test
再次看active控制台