Rabbitmq示例之发布订阅模式

上一篇 << 下一篇 >>>Rabbitmq示例之路由模式Routing


1.核心思想

一个生产者投递消息,可以被多个不同的队列实现消费;

2.实现原理

多个不同的队列绑定相同交换机,生产者只需要将消息投递到交换机之后,在由交换机将消息转发到所有绑定的队列实现消费。
优点:生产者只针对交换机,交换机可以在控制台绑定或解绑多个队列,代码不用任何的变动,操作便捷。

3.核心代码

/**
 * 生产者只需要关联交换机,交换机绑定了哪些队列由控制台设置。代码中定义了关联性,一旦控制台删除了,消费者也会收不到
 */
public class ProducerFanout {

    private static final String EXCHANGE_NAME = "fanout_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabitMQConnection.getConnection();
        Channel channel = connection.createChannel();
        String msg = "交换机消息发布了";
        channel.basicPublish(EXCHANGE_NAME, "", null, msg.getBytes());
        channel.close();
        connection.close();
    }
}

/**
 * 邮件消费者
 */
public class MailConsumer {
    private static final String QUEUE_NAME = "consumerFanout_email";
    private static final String EXCHANGE_NAME = "fanout_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        System.out.println("邮件消费者...");
        Connection connection = RabitMQConnection.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("邮件消费者获取消息:" + msg);
            }
        };
        channel.basicConsume(QUEUE_NAME, true, defaultConsumer);
    }
}

/**
 * 短信消费者
 */
public class SmsConsumer {
    private static final String QUEUE_NAME = "consumerFanout_sms";
    private static final String EXCHANGE_NAME = "fanout_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        System.out.println("短信消费者...");
        Connection connection = RabitMQConnection.getConnection();
        final Channel channel = connection.createChannel();
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "");
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                System.out.println("短信消费者获取消息:" + msg);
            }
        };
        channel.basicConsume(QUEUE_NAME, true, defaultConsumer);
    }
}

3.效果演示

配置上解绑了短信的队列,代码不用任何的改动,就会出现下面的输出了


推荐阅读:
<<<消息中间件的核心思想
<<<消息中间件常见问题汇总
<<<基于Netty简单手写消息中间件思路
<<<消息队列常用名词与中间件对比
<< << << << << << << << << << << << << << << << << << << << << << << << << << << << << << << <<

你可能感兴趣的:(Rabbitmq示例之发布订阅模式)