RabbitMQ Publish/Subscribe模式

该博客演示了如何在Java中使用RabbitMQ创建一个Fanout类型的交换机,并将消息广播到两个不同的队列中。通过创建`ps_exchange`交换机并将其绑定到`ps_queue1`和`ps_queue2`,生产者发送的消息会被同时分发到这两个队列。两个消费者`conTest`和`conTest1`分别监听`ps_queue1`和`ps_queue2`,接收到并打印消息。
摘要由CSDN通过智能技术生成

一个生产者,一个交换机,两个队列,两个消费者

 

声明一个Fanout类型的exchange,并且将exchange和queue绑定在一起,绑定的方式就是直接绑定。

让生产者创建一个exchange并且指定类型,和一个或多个队列绑定到一起。

public class PSTest {

    @Test
    public void pubTest() throws IOException {

        Connection connection = MQFactory.getConnection();

        Channel channel = connection.createChannel();

        //创建交换机  指定类型为fanout
        channel.exchangeDeclare("ps_exchange", BuiltinExchangeType.FANOUT);

        //创建队列
        channel.queueDeclare("ps_queue1",true,false,false,null);
        channel.queueDeclare("ps_queue2",true,false,false,null);

        //交换机跟队列绑定
        channel.queueBind("ps_queue1","ps_exchange","");
        channel.queueBind("ps_queue2","ps_exchange","");

        for (int i = 0; i < 10; i++) {

            channel.basicPublish("ps_exchange","",null,("msg:"+i).getBytes());

        }



    }

    @Test
    public void conTest() throws IOException {

        Connection connection = MQFactory.getConnection();

        Channel channel = connection.createChannel();

        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String s = new String(body, "utf-8");
                System.out.println("消费者1:" + s);
            }
        };

        channel.basicConsume("ps_queue1",true,defaultConsumer);

        System.in.read();
    }


    @Test
    public void conTest1() throws IOException {

        Connection connection = MQFactory.getConnection();

        Channel channel = connection.createChannel();

        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String s = new String(body, "utf-8");
                System.out.println("消费者2:" + s);
            }
        };

        channel.basicConsume("ps_queue2",true,defaultConsumer);

        System.in.read();
    }


}

 

 交换机分别发给两个队列

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值