RabbitMQ学习(三) 发布/订阅广播模式(fanout)

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上“编程不良人”大神的视频学习记录的笔记,如果眼花有记错的地方,希望能够提出,大家共同努力,谢谢。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值