RabbitMq是一种消息队列
什么是MQ
字面理解MQ即messgae queue,消息队列,是一种程序之间的通信方式;由sheng生产者写入消息并由消费者进行消费。
简单案例
springboot集成rabbitmq(linux 安装rabbitmq)
pom
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency>
然后在application.properties中配置rabbitmq
地址、用户名、密码都是在安装rabbitmq时配置的
spring.rabbitmq.host=192.168.2.149spring.rabbitmq.port=5672spring.rabbitmq.username=adminspring.rabbitmq.password=admin
配置queue
package com.stu.demo.rabbitmq;import org.springframework.amqp.core.Queue;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
/**
* rabbitMq配置文件
*
* @author [email protected]
* @create 2018-06-11 22:16
* @description
**/
@Configurationpublic class rebbitmqConfig {@Beanpublic Queue queueForOne() {return new Queue("rabbit_test_one");}}
发送消息
使用springboot默认的交换机
package com.stu.demo.rabbitmq;import org.springframework.amqp.core.AmqpTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;/*** 消息生产者** @author [email protected]* @create 2018-06-11 22:19* @description**/@Configurationpublic class rabbitmqSender {@Autowiredprivate AmqpTemplate template;public void send(){String messgae = "hello rabbit";this.template.convertAndSend("rabbit_test_one",messgae);}}
接受消息
package com.stu.demo.rabbitmq;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.annotation.Configuration;/*** @author [email protected]* @create 2018-06-11 22:21* @description**/@Configurationpublic class rabbitmqReceiver {private Logger logger = LoggerFactory.getLogger(rabbitmqReceiver.class);public void getMessage(String msg){logger.info(msg);}}
测试一下
使用swagger2 作为接口api文档,使用swagger
package com.stu.demo.rabbitmq;import io.swagger.annotations.ApiImplicitParam;import io.swagger.annotations.ApiOperation;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;/*** @author [email protected]* @create 2018-06-12 21:11* @description**/@RestControllerpublic class rabbitController {@Autowiredprivate rabbitmqSender rabbitmqSender;@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")@ApiImplicitParam(name = "msg", value = "rabbitMq信息", required = true, dataType = "String", paramType = "path")@RequestMapping(value = "/sendMqMsg/{msg}", method = RequestMethod.GET)public void sendMqMsg(@PathVariable(value = "msg") String msg){rabbitmqSender.send(msg);}}