先了解什么是Mq
消息队列,是基础数据结构中“先进先出”的一种数据结构。指把要传输的数据(消息)放在队列中,用队列机制来实现消息传递——生产者产生消息并把消息放入队列,然后由消费者去处理。消费者可以到指定队列拉取消息,或者订阅相应的队列,由MQ服务端给其推送消息。
Mq的优势
(1)异步。调用者无需等待。
(2)解耦。解决了系统之间耦合调用的问题。
(3)消峰。抵御洪峰流量,保护了主业务。
Mq的落地产品
本次主要做的实验是SpringBoot整合ActiveMq实现消息队列的生产消费。以及主题的生产消费。
第一步添加ActiveMq与SpringBoot的整合依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
<version>2.7.8</version>
</dependency>
第一步实现消息队列模式
配置yml配置文件
spring:
#配置ActiveMq的服务器地址
activemq:
broker-url: tcp://localhost:61616
jms:
# 订阅与发布模式打开/关闭
pub-sub-domain: false
写一个生产者的接口
我在service层中注入了
@Autowired
private JmsMessagingTemplate messagingTemplate;
方法是
@Override
public void sendMessage(int random) {
System.out.println("发送消息随机数"+random);
ActiveMQQueue activeMQQueue = new ActiveMQQueue("money.id");
try {
messagingTemplate.convertAndSend(activeMQQueue,random);
}catch (Exception e){
throw new RuntimeException(e.getMessage());
}
}
在控制器中调用
/**
* MQ生产者生产队列消息
*/
@RequestMapping("/product")
public AjaxResult product(){
Random random = new Random();
carfeeService.sendMessage(random.nextInt(100));
return AjaxResult.success("生产成功");
}
配置消费者
@Component
public class MessageListerner {
@JmsListener(destination = "${queue}")
public void receive1(String id){
System.out.println("消费队列1 接收到mq的信息"+id);
}
@JmsListener(destination = "${queue}")
public void receive2(String id){
System.out.println("消费队列2 接收到mq的信息"+id);
}
}
配置了两个消费者进行消费消息。执行结果
订阅与发布模式
需要修改Yml配置文件 pub-sub-domain: true
spring:
#配置ActiveMq的服务器地址
activemq:
broker-url: tcp://localhost:61616
jms:
# 订阅与发布模式打开/关闭
pub-sub-domain: true
然后生产者核心代码
@Override
public void subProduct(String message) {
System.out.println("发送订阅与发布 "+message);
ActiveMQTopic activeMQTopic = new ActiveMQTopic("topic");
messagingTemplate.convertAndSend(activeMQTopic,message);
}
在控制器中的调用
@RequestMapping("subProduct")
public AjaxResult subProduct(){
Random random = new Random();
try{
String[] messages=new String[]{"你好世界","鸡你太美","111","222"};
carfeeService.subProduct(messages[random.nextInt(messages.length)]);
}catch (Exception e){
logger.info(e.getMessage());
}
return AjaxResult.success();
}
配置订阅与发布的消费者
因为是主题 索引几个消费者订阅 者几个消费者都会收到消息。类似微信公众号。
@Component
public class MessageListerner {
@JmsListener(destination = "topic")
public void receiveSub1(String message){
System.out.println("消费主题1 接收到mq的信息"+message);
}
@JmsListener(destination = "topic")
public void receiveSub2(String message){
System.out.println("消费主题2 接收到mq的信息"+message);
}
@JmsListener(destination = "topic")
public void receiveSub3(String message){
System.out.println("消费主题3 接收到mq的信息"+message);
}
@JmsListener(destination = "topic")
public void receiveSub4(String message){
System.out.println("消费主题4 接收到mq的信息"+message);
}
}
测试结果 可以实现。