1、在pom文件中引入对应jar包
<!--activeMQ start-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-pool</artifactId>
<!-- <version>5.7.0</version> -->
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
<!--activeMQ end-->
2、application.yml文件配置activemq;对于监听Listener使用注解的形式
#activeMQ的配置
activemq:
broker-url: tcp://localhost:61616
in-memory: true
pool:
enabled: false #如果此处设置为true,需要加如下的依赖包,否则会自动配置失败,报JmsMessagingTemplate注入失败
3、创建生产者类,生产者代码如下:
/**
* Created by Administrator on 2018/7/27.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootJmsApplicationTests {
@Test
public void contextLoads() throws InterruptedException, JMSException {
Destination destination = new ActiveMQQueue("queue_demo");
//创建与JMS服务的连接:ConnectionFactory被管理的对象,由客户端创建,用来创建一个连接对象
ConnectionFactory connectionfactory = new ActiveMQConnectionFactory("tcp://localhost:61616");
//获取连接,connection一个到JMS系统提供者的活动连接
javax.jms.Connection connection = connectionfactory.createConnection();
//打开会话,一个单独的发送和接受消息的线程上下文
Session session =connection.createSession(false,Session.AUTO_ACKNOWLEDGE );
Queue queue = new ActiveMQQueue("queue_demo");
MessageProducer msgProducer = session.createProducer(queue);
Message msg = session.createTextMessage("文本1");
msgProducer.send(msg);
System.out.println("文本消息已发送");
}
}
4、编写消费者代码,代码如下:
/**
* Created by Administrator on 2018/7/27.
*/
@Component
public class Consumer2 {
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener(destination = "queue_es")
public void receiveQueue(String mapStr) {
System.out.println("接受的消息:"+mapStr);
}
}
5、运行生产者(本处是test注解的测试代码),直接运行,结果如下
发送端:
接收端:
ps:如果想设置为独占消息消费模式,只需将消费者的代码@JmsListener注解处修改为如下代码:
@JmsListener(destination = "queue_es?consumer.exclusive=true")就可以设置此消费者为独占消息消费模式,队列里的任务会玩先后顺序被这个消费者处理掉