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.149
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.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 jushangzhi@novacloud.com
* @create 2018-06-11 22:16
* @description
**/
@Configuration
public class rebbitmqConfig {
@Bean
public 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 jushangzhi@novacloud.com
* @create 2018-06-11 22:19
* @description
**/
@Configuration
public class rabbitmqSender {
@Autowired
private 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 jushangzhi@novacloud.com
* @create 2018-06-11 22:21
* @description
**/
@Configuration
public 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 jushangzhi@novacloud.com
* @create 2018-06-12 21:11
* @description
**/
@RestController
public class rabbitController {
@Autowired
private 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);
}
}