RabbitMQ04_fanout广播模型
生产者发送消息给交换机(Exchange)
交换机将消息发送给所有绑定的队列
队列的消费者都能拿到消息,实现了一条消息被多个消费者消费
消息生产者:
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//将通道声明指定的交换机
//参数1:交换机名称(自定义) 参数2:交换机的类型 fanout表示广播类型
channel.exchangeDeclare("logs", "fanout");
//发送消息给交换机
//参数2:在广播模型中routingKey没有意义,填空字符串
channel.basicPublish("logs", "", null, "fanout type message".getBytes());
RabbitMQUtils.closeConnectionAndChannel(channel, connection);
}
消费者1:
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
//通道绑定交换机
channel.exchangeDeclare("logs", "fanout");
//创建临时队列
String queueName = channel.queueDeclare().getQueue();
//绑定交换机和队列,参数3:routingKey在fanout中无意义
channel.queueBind(queueName, "logs", "");
//消费消息
channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
System.out.println("消费者1:"+new String(body));
}
});
}
消费者2:
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("logs", "fanout");
String queueName = channel.queueDeclare().getQueue();
channel.queueBind(queueName, "logs", "");
channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
System.out.println("消费者2:"+new String(body));
}
});
}
每当消息生产者生产消息时,消费者1和消费者2都能够消费消息,这就是广播模式
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blucoding.blog.csdn.net/article/details/109533788
内容来源于网络,如有侵权,请联系作者删除!