springboot 整合ActiveMQ

谁说我不能喝 提交于 2020-03-07 03:25:15

简介

消息队列可以有效实现服务解耦,并提高系统的可靠性和可扩展性。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
在这里插入图片描述

即可看到消息入队和被消费。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!