RabbitMQ的发布订阅消息模型代码实战

此博客展示了如何使用RabbitMQ实现广播(Fanout)模式的消息发送与接收。发送端创建连接并发布消息到fanout类型的exchange,而消费端则创建连接,声明exchange并绑定队列,接收并打印接收到的消息。
摘要由CSDN通过智能技术生成
//发送端
public class Send {

​

    private final static String EXCHANGE_NAME = "exchange_fanout";

​

    public static void main(String[] argv) throws Exception {

        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("10.211.55.13");

        factory.setUsername("admin");

        factory.setPassword("password");

        factory.setVirtualHost("/dev");

        factory.setPort(5672);

​

        /**

         * 消息生产者不用过多操作,只需要和交换机绑定即可

         */

        try (//创建连接

             Connection connection = factory.newConnection();

             //创建信道

             Channel channel = connection.createChannel()) {

​

            //绑定交换机,fanout扇形,即广播类型

            channel.exchangeDeclare(EXCHANGE_NAME,BuiltinExchangeType.FANOUT);

​

            String message = "Hello World pub !";

            channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes(StandardCharsets.UTF_8));

            System.out.println(" [x] Sent '" + message + "'");

​

        }

    }

}
//消费端

public class Recv1 {

​

    private final static String EXCHANGE_NAME = "exchange_fanout";

​

    public static void main(String[] argv) throws Exception {

        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("10.211.55.13");

        factory.setUsername("admin");

        factory.setPassword("password");

        factory.setVirtualHost("/dev");

        factory.setPort(5672);

​

        //消费者一般不增加自动关闭

        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

​

        //绑定交换机,fanout扇形,即广播类型

        channel.exchangeDeclare(EXCHANGE_NAME,BuiltinExchangeType.FANOUT);

​

        //获取队列(排它队列)

        String queueName = channel.queueDeclare().getQueue();

​

        //绑定队列和交换机,fanout交换机不用指定routingkey

        channel.queueBind(queueName,EXCHANGE_NAME,"");

​

​

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {

            String message = new String(delivery.getBody(), "UTF-8");

            System.out.println(" [x] Received '" + message + "'");

        };

​

        //自动确认消息

        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });

​

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值