基本简介
erlang语言(支持多核,分布式特性)开发。
基于AMQP(Advanced Message Queue 高级消息队列协议)协议实现。
应用场景
- 异步处理任务
- 应用解耦。(生产方通过MQ与消费方交互)
优势
- SpringBoot默认集成!
- 高并发性能优秀。
结构
Broker:即RabbitMQ扮演的角色,其自身包含Exchange(路由交换机)和Queue两个部分。
客户端分为:Producer生产者和Cusumer消费者
必要依赖添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
YML 基本配置
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
helloworld (SpringBoot)
配置类
@Configuration
public class RabbitMQConfig {
static final String QUEUE = "direct_queue";
/**
* Direct模式
* @return
*/
@Bean
public Queue directQueue() {
// 第一个参数是队列名字, 第二个参数是指是否持久化
return new Queue(QUEUE, true);
}
}
生产者
// 注入 Template
@Autowired
RabbitTemplate rabbitTemplate;
// 使用发送消息方法
/**
* 参数:
* 1、Queue名称
* 2、消息内容 可以为任意T类型
*/
rabbitTemplate.convertAndSend(RabbitmqConfig.QUEUE,t);
消费者
@RabbitListener(queues = RabbitMQConfig.QUEUE)
public void receiver(T t){
log.info(t);
}
此案例中系统默认指定啦交换机
常用模式Topic
路由模式:
1、每个消费者监听自己的队列,并且设置带统配符的routingkey。
2、生产者将消息发给broker,由交换机根据routingkey来转发消息到指定的队列。
此时,指定的routingkey可以发给适合的消费者来进行消费
@Configuration
public class RabbitMQConfig {
public static final String TOPIC_QUEUE1 = "topic.queue1";
public static final String TOPIC_QUEUE2 = "topic.queue2";
public static final String TOPIC_EXCHANGE = "topic.exchange";
/**
* Topic模式
* @return
*/
@Bean
public Queue topicQueue1() {
return new Queue(TOPIC_QUEUE1);
}
@Bean
public Queue topicQueue2() {
return new Queue(TOPIC_QUEUE2);
}
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(TOPIC_EXCHANGE);
}
@Bean
public Binding topicBinding1() {
return BindingBuilder.bind(topicQueue1()).to(topicExchange()).with("tony.message");
}
// #表示通配符
@Bean
public Binding topicBinding2() {
return BindingBuilder.bind(topicQueue2()).to(topicExchange()).with("tony.#");
}
}
生产者
@Component
@Slf4j
public class Sender {
@Autowired
private AmqpTemplate amqpTemplate;
public void sendTopic() {
User user1 = new User();
user1.setUserId("123456");
user1.setName("lizhencheng");
User user2 = new User();
user2.setUserId("456789");
user2.setName("张三");
log.info("【sendTopic已发送消息】");
// 第一个参数:TopicExchange名字
// 第二个参数:Route-Key
// 第三个参数:要发送的内容
this.amqpTemplate.convertAndSend(RabbitMQConfig.TOPIC_EXCHANGE, "tony.message", user1 );
this.amqpTemplate.convertAndSend(RabbitMQConfig.TOPIC_EXCHANGE, "tony.anything", user2);
}
}
消费者
@Component
@Slf4j
public class Receiver {
// queues是指要监听的队列的名字
@RabbitListener(queues = RabbitMQConfig.TOPIC_QUEUE1)
public void receiveTopic1(User user) {
log.info("【receiveTopic1监听到消息】" + user.toString());
}
@RabbitListener(queues = RabbitMQConfig.TOPIC_QUEUE2)
public void receiveTopic2(User user) {
log.info("【receiveTopic2监听到消息】" + user.toString());
}
}
其他模式:
简单模式:一个生产者,一个消费者
work模式:一个生产者,多个消费者,每个消费者获取到的消息唯一。
订阅模式:一个生产者发送的消息会被多个消费者获取。
路由模式:发送消息到交换机并且要指定路由key ,消费者将队列绑定到交换机时需要指定路由key
topic模式:将路由键和某模式进行匹配,此时队列需要绑定在一个模式上,“#”匹配一个词或多个词,“*”只匹配一个词。