简介
消息队列可以有效实现服务解耦,并提高系统的可靠性和可扩展性。ActiveMQ 是一个开源消息中间件,Apache ActiveMQ 对Spring 提供了支持,可以非常便捷的嵌入Spring。
异步消息中有两个很重要的概念,即消息代理(message broker)和目的地(destination),消息发送后将由消息代理接管。
异步消息主要有两种形式的目的地:队列(queue) 和主题(topic)。队列用于点对点(point to point)消息通信;主题用于发布订阅(publish/subscribe)的通讯。
二.流程
1.下载安装activemq并配置相关授权
2.pom.xml 引入activemq 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
3.application.yml 配置activemq
4.HelloController.java
package com.vincent.controller;
import com.vincent.model.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.jms.Message;
@RestController
public class HelloController {
@Autowired
private JmsMessagingTemplate messagingTemplate;
@RequestMapping("/hello")
public R hello(String name,Integer age){
messagingTemplate.convertAndSend("com.vincent.test.queue",name);
return R.ok("hello world");
}
@JmsListener(destination = "com.vincent.test.queue")
public void recvMsg(Message message){
System.out.println(message);
}
}
Spring对JMS 提供了JmsTemplate 来发送消息
@JmsListener 是Spring 提供的一个特性,用于简化JMS 开发,只需在这个注解的destination 属性指定监听的目的地,即可接收该目的地的信息。
三.测试
1.登录ActiveMQ 后台管理:http://localhost:8161
2.运行spring boot 项目:
项目运行后如果没有指定的目的地将会创建一个目的地
3.访问:http://localhost:8080/hello?name=vincent
发送消息:
即可看到控制台输出了我们发送的消息。
4.刷新activemq 管理控制台:http://localhost:8161/admin/queues.jsp
即可看到消息入队和被消费。
来源:CSDN
作者:奶茶37.2℃
链接:https://blog.csdn.net/Zllvincent/article/details/104703917