RabbitMQ(Java操作-广播模型)

1 - maven 依赖

 <dependency>
     <groupId>com.rabbitmq</groupId>
     <artifactId>amqp-client</artifactId>
     <version>5.7.2</version>
 </dependency>

2 - 生产者

public class Provider {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.181.133");
        factory.setPort(5672);
        factory.setVirtualHost("/ems");
        factory.setUsername("root");
        factory.setPassword("root");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        /**
         * 声明交换机
         *  参数1:交换机名称
         *  参数2:交换机类型
         */
        channel.exchangeDeclare("logs","fanout");
        /**
         * 发送消息
         *  参数1:交换机名称
         *  参数2:队列名称(fanout模型不需要指定队列)
         *  参数3:添加额外参数
         *  参数4;发送的消息
         */
        channel.basicPublish("logs","",null,"hello".getBytes());
        /**
         * 释放资源
         */
        channel.close();
        connection.close();
    }
}

3 - 消费者

public class Consumer1 {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.181.133");
        factory.setPort(5672);
        factory.setVirtualHost("/ems");
        factory.setUsername("root");
        factory.setPassword("root");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        /**
         * 通道绑定交换机
         *  参数1:交换机名称
         *  参数2:交换机模型fanout模型
         */
        channel.exchangeDeclare("logs","fanout");

        /**
         * 获取一个临时队列名称
         */
        String queue = channel.queueDeclare().getQueue();
        /**
         * 绑定交换机和队列
         *  参数1:队列的名称
         *  参数2:交换机的名称
         *  参数3:路由key(fanout模型没有)
         */
        channel.queueBind(queue,"logs","");
        channel.basicConsume("",true,new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(new String(body));
            }
        });


    }
}

fanout模型,只要消费者都存在,所有消费者都能接收到,广播模式

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值