概述:
RabbitMQ 即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用。消息中间件最主要的作用是解耦,中间件最标准的用法是生产者生产消息传送到队列,消费者从队列中拿取消息并处理,生产者不用关心是谁来消费,消费者不用关心谁在生产消息,从而达到解耦的目的。在分布式的系统中,消息队列也会被用在很多其它的方面,比如:分布式事务的支持,RPC的调用等等。
1.Rabbit MQ 介绍及安装
1).安装包,使用说明,详见官网
2).https://www.rabbitmq.com
2.Rabbit MQ jar 引用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
3.Rabbit MQ 生产者示例
1).创建队列
2).类配置@Configuration
3).使用topic模式
4).使用ampqTemplate.convertAndSend("队列名称",data);
/**
* 创建队列
*/
@Configuration
public class ProductConfig {
@Bean("sendTemplate")
public Queue sendTemplate() {
return new Queue("wx.queue.sendtemplate");
}
@Bean("sendsms")
public Queue sendsms(){
return new Queue("wx.queue.sendsms");
}
}
/**
* MQ 生产者
* @author andy
*
*/
@Slf4j
@Service
@EnableScheduling
public class MessageProductService {
@Autowired
private AmqpTemplate amqpTemplate;
/**
* 发送回访任务
* @Scheduled(fixedRate = 50000)
*/
public void sendTemplateMessage() {
Date date = new Date();
String data = "测试";
log.info("发送信息 : " + date + data);
amqpTemplate.convertAndSend("wx.queue.sendsms, data);
}
/**
* 发送任务
*
*/
@Scheduled(fixedRate = 50000)
public void sendTemplateMessage() {
Date date = new Date();
String data = "测试";
log.info("发送信息 : " + date + data);
amqpTemplate.convertAndSend("wx.queue.sendtemplate", data);
}
}
4.Rabbit MQ 消费者示例
1).创建队列
2).方法配置接收队列信息-@RabbitListener(queues = "队列名称")
3).消息输出
/**
* 创建队列
* @author andy
*/
@Configuration
public class CustomerConfig {
@Bean("sendTemplate")
public Queue sendTemplate() {
return new Queue("wx.queue.sendtemplate");
}
@Bean("sendsms")
public Queue sendsms(){
return new Queue("wx.queue.sendsms");
}
}
/**
* 消费者
* MQ消息业务处理
*/
@Slf4j
@Service
public class MessageClientService{
@Autowired
private WxMessage wxMessage;
/**
* 监听模板消息
* @param jsonData
*/
@RabbitListener(queues = "wx.queue.sendtemplate")
public void sendTemplateMessage(String jsonData) {
log.info("sendTemplateMessage: request from message queue---begin");
String str= wxMessage.handleMessage(jsonData);
log.info("sendTemplateMessage: request from message queue---end " + str);
}
/**
* 监听短信
* @param jsonData
*/
@RabbitListener(queues = "wx.queue.sendsms")
public void sendSmsMessage(String jsonData) {
log.info("sendSmsMessage: request from message queue---begin");
String str = wxMessage.handleMessage(jsonData);
log.info("sendSmsMessage: request from message queue---end " + str);
}
}
5.Rabbit MQ 相关config 及 test
1).config Rabbit MQ 账号信息
spring:
rabbitmq:
host: localhost
port: 5672
username: test1
password: test1
6.交换机配置队列信息