JAVA操作RabbitMQ-发布订阅模式

发布/订阅模式(Publish/Subscribe):将消息发送给多个消费者。做到一次发布,消费多个。RabbitMQ不会直接通过生产者发送到消息给队列,而是生产者只会发送消息到exchange 交换机,exchange接收消息,把消息推送到消息队列中。exchange必须知道如何处理接收到的消息 ,推送到哪个队列中,还是放弃,这个是由它的类型来决定 。
exchange有四种类型:fanout,direct,topic,headers
发布订阅模式使用fanout类型,fanout消息类型可以把消息广播到所有队列中。

P:消息的生产者
C:消息的消费者
红色:队列
X:交换机

JAVA操作RabbitMQ-发布订阅模式_第1张图片

 1. pom.xml引入rabbitmq依赖


     com.rabbitmq
     amqp-client
     5.13.1

2. 生产者

public class Producer {

    public static void main(String[] args) {
        // 创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("123456");
        connectionFactory.setVirtualHost("/");
        // 创建Connection

        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection("生产者");
            channel = connection.createChannel();

            String message = "hello message";
            String exchangeName = "fanout-exchange"; //交换机名称
            String type = "fanout"; //交换机类型

            // 创建交换机
            channel.exchangeDeclare(exchangeName, type, true);

            //创建队列
            // 队列名称,是否持久化,是否独占,是否自动删除(当最后一条消息消费完毕后自动删除),附加属性
            channel.queueDeclare("fanout-queue1", true, false, false, null);
            channel.queueDeclare("fanout-queue2", true, false, false, null);

            // 绑定交换机
            channel.queueBind("fanout-queue1", exchangeName, "");
            channel.queueBind("fanout-queue2", exchangeName, "");

            // 发送消息到队列
            // exchange,routingKey, props,message body
            channel.basicPublish(exchangeName, "", null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println("消息发送成功");

        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException | TimeoutException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }
}

3. 消费者

public class Consumer {

    public static class C implements Runnable {

        @Override
        public void run() {
            Thread thread = Thread.currentThread();
            // 创建链接
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("127.0.0.1");
            connectionFactory.setPort(5672);
            connectionFactory.setUsername("admin");
            connectionFactory.setPassword("123456");
            connectionFactory.setVirtualHost("/");
            // 创建Connection

            Connection connection = null;
            Channel channel = null;
            try {
                connection = connectionFactory.newConnection("消费者");
                channel = connection.createChannel();
                String queueName = thread.getName();

                channel.basicConsume(queueName, true,
                        (consumerTag, message) -> System.out.println(queueName + ":收到消息:" + new String(message.getBody(), StandardCharsets.UTF_8)),
                        consumerTag -> System.out.println("消费者取消订阅"));

                while (true) {
                    // 防止程序结束
                }
            } catch (IOException | TimeoutException e) {
                e.printStackTrace();
            } finally {
                if (channel != null && channel.isOpen()) {
                    try {
                        channel.close();
                    } catch (IOException | TimeoutException e) {
                        e.printStackTrace();
                    }
                }
                if (connection != null && connection.isOpen()) {
                    try {
                        connection.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    public static void main(String[] args) {
        new Thread(new C(),"fanout-queue1").start();
        new Thread(new C(),"fanout-queue2").start();

    }

你可能感兴趣的:(rabbitmq,rabbitmq,java)