Java implements rabbitmq publish/subscribe model (Publish/Subscribe queues), producer consumer exchange message queue

The publish/subscribe model is also known as the fan-out model, or the broadcast model. There can be multiple consumers. Each consumer has its own queue. Each queue must be bound to the exchange. Messages sent by the producer only need to be sent to The switch, then the switch decides which queues to send to, and the producer cannot decide by himself. The exchange will send the message to all the bound queues to achieve one-to-many, and one message is consumed by multiple consumers.

Insert picture description here
As you can see, this model requires switch modules. We can see many switches available for use in the background management interface. Of course, you can also declare the switches you need.
Insert picture description hereEach virtual host generates multiple types of switches by default. Here we choose a fanout type switch named amqp.fanout to test.

  1. Producer
public class Provider {
    
    
    public void send() throws IOException, TimeoutException {
    
    
        Connection connection = null;
        Channel channel = null;
        try {
    
    
            connection = ConnectionUtils.getConnection();
            // 获取连接通道
            channel = connection.createChannel();
            // 定义通道对应的交换机 参数一:交换机名称 参数二:教会及类型 fanout 广播模型
            channel.exchangeDeclare("amqp.fanout","fanout");
            // 发送消息
            channel.basicPublish("amqp.fanout","",null,("fanout message " + System.currentTimeMillis()).getBytes());
        }finally {
    
    
            if (channel !=null && channel.isOpen()) {
    
    
                channel.close();
            }
            if (connection != null && connection.isOpen()) {
    
    
                connection.close();
            }
        }
    }

    public static void main(String[] args) throws IOException, TimeoutException {
    
    
        Provider provider = new Provider();
        provider.send();
    }
}

After obtaining the channel through the connection, use channel.exchangeDeclare("amqp.fanout","fanout"); to declare the switch. If the switch does not exist, rabbitmq will automatically create it. When sending a message, specify the exchange as amqp.fanout, and the second parameter is Empty, use temporary queue.

  1. consumer
public class Consumer01 {
    
    
    public void consume() throws IOException, TimeoutException {
    
    
        Connection connection = ConnectionUtils.getConnection();
        // 获取连接通道
        final Channel channel = connection.createChannel();
        // 绑定交换机
        channel.exchangeDeclare("amqp.fanout","fanout");
        //创建临时队列
        String queueName = channel.queueDeclare().getQueue();
        // 绑定交换机和队列
        channel.queueBind(queueName,"amqp.fanout","");
        // 每次只能消费一个消息
        channel.basicQos(1);
        // 消费消息
        channel.basicConsume(queueName, false, new DefaultConsumer(channel) {
    
    
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    
    
                System.out.println("消费消息:" + new String(body));
                try {
    
    
                    Thread.sleep(10);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
                //参数一:确认队列中的那个消息  参数二:是否开启多个消息同时确认
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
    public static void main(String[] args) throws IOException, TimeoutException {
    
    
        Consumer01 consumer = new Consumer01();
        consumer.consume();
    }
}

To reduce space here, readers can copy the code of Consumer01 to generate Consumer02 or multiple consumer classes

  1. The test
    starts all consumers and monitors the exchange through a temporary queue. At this time, the running producer publishes the message, and multiple consumers can receive the message sent by the switch at the same time.
    Consumer 1:
    Insert picture description hereConsumer 2:
    Insert picture description hereMultiple consumers receive the same message at the same time, and the producer is run again. The message is sent to multiple consumers bound to the switch in the form of broadcast. Among them, the consumer and the switch Connect via temporary queue.

Guess you like

Origin blog.csdn.net/qq_41885819/article/details/112870827