RabbitMQ的发布订阅模式:fanout
消息发送流程说明
- 可以有多个消费者
- 每个消费者都有自己的队列(queue)
- 每个队列都要绑定到交换机(Exchange)(都是一些临时队列)
- 生产者发送的消息只能发送到交换机,交换机来决定要发给那个队列,生产者无法决定。
- 交换机将消息发送给绑定过的所有队列
- 队列的消费者都能拿到消息,实现一条消息被多个消费者消费
代码实现
生产者
package com.mahy.notes.fanout;
import com.mahy.utils.RabbitMQUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
/**
* @Auther : mahy
* @Date : 2020/7/27 21:56
* @Description : 发布/订阅模式的生产者--广播类型.
*/
public class Provider {
public static void main(String[] args) throws IOException {
//创建连接
Connection connection = RabbitMQUtils.getConnection();
//创建通道
Channel channel = connection.createChannel();
/**
* 给通道绑定交换机-声明交换机
* 参数一: 交换机名称
* 参数二: 交换机类型 fanout 是指广播类型
*/
channel.exchangeDeclare("laoma","fanout");
/**
* 发送消息
* 参数一:将消息发送的交换机名称
* 参数二:这个在广播模式下没有意义,传个空字符串
* 参数三: 消息的一些其他设置 这边给个空值
* 参数四: 发送的消息内容 Byte Array类型
*/
channel.basicPublish("laoma","",null,"fanout type message".getBytes());
//关闭连接
RabbitMQUtils.closeConnection(channel,connection);
}
}
消费者
消费者代码一样,我这边创建了三个,分别为Customer1 、Customer2 、Customer3,只展示Customer1的代码。
package com.mahy.notes.fanout;
import com.mahy.utils.RabbitMQUtils;
import com.rabbitmq.client.*;
import java.io.IOException;
/**
* @Auther : mahy
* @Date : 2020/7/27 22:02
* @Description : Please describe here.
*/
public class Customer1 {
public static void main(String[] args) throws IOException {
//建立连接
Connection connection = RabbitMQUtils.getConnection();
//创建通道
Channel channel = connection.createChannel();
//声明交换机
channel.exchangeDeclare("laoma","fanout");
//获取临时队列的名称
String queueName = channel.queueDeclare().getQueue();
//绑定交换机跟队列
channel.queueBind(queueName,"laoma","");
//消费消息
channel.basicConsume("",true,new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1消费:" + new String(body));
}
});
}
}
结果
运行生产者发送一条消息,三个消费者的消费情况如下图:
消费者1
消费者2
消费者3
总结:从图中的结果可以看出,三个消费者同时消费了生产者发送的这条消息,这个就是发布订阅模式。
最后的说明
这是观看BILIBILI上“编程不良人”大神的视频学习记录的笔记,如果眼花有记错的地方,希望能够提出,大家共同努力,谢谢。