RabbitMQ消息中间件(三):工作模式之工作队列(Work queues)


Work Queues: 与入门程序的简单模式相比,多了一个或一些消费端,多个消费端共同消费同一个队列中的消息。

应用场景: 对于任务过重或任务较多情况使用工作队列可以提高任务处理的速度。

说明: 在一个队列中如果有多个消费者,那么消费者之间对于同一个消息的关系是 竞争 的关系。

RabbitMQ消息中间件(三):工作模式之工作队列(Work queues)_第1张图片
说明:

  • P:生产者,也就是要发送消息的程序
  • C:消费者:消息的接受者,会一直等待消息到来。
  • queue:消息队列,图中红色部分

一、生产者Module

(1)pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>rabbitmq-demoartifactId>
        <groupId>net.xiaofgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>rabbitmq-producerartifactId>

    <properties>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
        <project.build.sourceEncoding>utf-8project.build.sourceEncoding>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>com.rabbitmqgroupId>
            <artifactId>amqp-clientartifactId>
            <version>5.6.0version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.8.0version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                configuration>
            plugin>
        plugins>
    build>

project>

(2)生产者类

package net.xiaof.producer;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * @author zhangxh
 * @Description: 生产者
 * @date 2020-12-14
 */
public class Producer_WorkQueues {

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

        //1.创建连接工厂,设置相关连接参数
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.116.161");
        factory.setPort(5672);
        factory.setVirtualHost("/myhost");
        factory.setUsername("xiao");
        factory.setPassword("xiao");

        //2. 创建连接Connection
        Connection connection = factory.newConnection();

        //3. 创建Channel
        Channel channel = connection.createChannel();

        //4. 声明队列Queue
        /**
         * 【API说明】:
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map arguments)
         * 参数:
         * (1)String queue:队列名称。如果当前队列名称不存在,则会创建该队列,否则不会创建
         * (2)boolean durable:是否持久化。即队列在服务器重启后是否还存在
         * (3)boolean exclusive:是否独占。只能有一个消费者监听这队列;当Connection关闭时,是否删除队列
         * (4)boolean autoDelete:是否自动删除。如果为true,至少有一个消费者连接到这个队列,之后所有与这个队列连接的消费者都断开时,队列会自动删除。
         * (5)Map arguments:附带参数。队列的其他属性,例如:x-message-ttl、x-expires、x-max-length、x-maxlength-bytes、x-dead-letter-exchange、x-dead-letter-routing-key、x-max-priority
         */
        channel.queueDeclare("work_queue", true, false, false, null);

        //5. 发布消息
        /**
         * 【API说明】:
         * basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)
         * 参数:
         * (1)String exchange:交换机名称。简单模式下交换机会使用默认的 ""
         * (2)String routingKey:路由key
         * (3)BasicProperties props:配置信息
         * (4)byte[] body:发送消息数据
         */
        String bodyMsg = "hello rabbitmq~~~好的";
        channel.basicPublish("", "work_queue", null, bodyMsg.getBytes());

        //6. 关闭资源
        channel.close();
        connection.close();

    }

}

二、消费者Module

(1)pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>rabbitmq-demoartifactId>
        <groupId>net.xiaofgroupId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>rabbitmq-consumerartifactId>

    <properties>
        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>
        <project.build.sourceEncoding>utf-8project.build.sourceEncoding>
    properties>

    <dependencies>
        
        <dependency>
            <groupId>com.rabbitmqgroupId>
            <artifactId>amqp-clientartifactId>
            <version>5.6.0version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <version>3.8.0version>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                configuration>
            plugin>
        plugins>
    build>

project>

(2)消费者类1

package net.xiaof.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author zhangxh
 * @Description:
 * @date 2020-12-14
 */
public class Consumer_WorkQueues1 {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂,设置相关连接参数
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.116.161");
        factory.setPort(5672);
        factory.setVirtualHost("/myhost");
        factory.setUsername("xiao");
        factory.setPassword("xiao");

        //2. 创建连接Connection
        Connection connection = factory.newConnection();

        //3. 创建Channel
        Channel channel = connection.createChannel();

        //4. 声明队列Queue
        /**
         * 【API说明】:
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map arguments)
         * 参数:
         * (1)String queue:队列名称。如果当前队列名称不存在,则会创建该队列,否则不会创建
         * (2)boolean durable:是否持久化。即队列在服务器重启后是否还存在
         * (3)boolean exclusive:是否独占。只能有一个消费者监听这队列;当Connection关闭时,是否删除队列
         * (4)boolean autoDelete:是否自动删除。如果为true,至少有一个消费者连接到这个队列,之后所有与这个队列连接的消费者都断开时,队列会自动删除。
         * (5)Map arguments:附带参数。队列的其他属性,例如:x-message-ttl、x-expires、x-max-length、x-maxlength-bytes、x-dead-letter-exchange、x-dead-letter-routing-key、x-max-priority
         */
        channel.queueDeclare("work_queue", true, false, false, null);

        //5. 接收消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             * 回调方法,当收到消息后,会自动执行该方法
             * void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
             * 参数:
             * (1)String consumerTag:标识
             * (2)Envelope envelope:获取一些信息,交换机,路由key...
             * (3)AMQP.BasicProperties properties:配置信息
             * (4)byte[] body:数据
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
//                System.out.println("consumerTag:" + consumerTag);
//                System.out.println("Exchange:" + envelope.getExchange());
//                System.out.println("RoutingKey:" + envelope.getRoutingKey());
//                System.out.println("properties:" + properties);
                System.out.println("body:" + new String(body));
            }
        };
        /**
         * 【API说明】:
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数:
         * (1)String queue:队列名称
         * (2)boolean autoAck:是否自动确认
         * (3)Consumer callback:回调对象
         */
        channel.basicConsume("work_queue", true, consumer);

        //6.关闭资源(消费者需要监听生产者消息,这里不关闭)

    }

}

(3)消费者类2(消费者类1内容相同)

package net.xiaof.consumer;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author zhangxh
 * @Description:
 * @date 2020-12-14
 */
public class Consumer_WorkQueues2 {

    public static void main(String[] args) throws IOException, TimeoutException {

        //1.创建连接工厂,设置相关连接参数
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.116.161");
        factory.setPort(5672);
        factory.setVirtualHost("/myhost");
        factory.setUsername("xiao");
        factory.setPassword("xiao");

        //2. 创建连接Connection
        Connection connection = factory.newConnection();

        //3. 创建Channel
        Channel channel = connection.createChannel();

        //4. 声明队列Queue
        /**
         * 【API说明】:
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map arguments)
         * 参数:
         * (1)String queue:队列名称。如果当前队列名称不存在,则会创建该队列,否则不会创建
         * (2)boolean durable:是否持久化。即队列在服务器重启后是否还存在
         * (3)boolean exclusive:是否独占。只能有一个消费者监听这队列;当Connection关闭时,是否删除队列
         * (4)boolean autoDelete:是否自动删除。如果为true,至少有一个消费者连接到这个队列,之后所有与这个队列连接的消费者都断开时,队列会自动删除。
         * (5)Map arguments:附带参数。队列的其他属性,例如:x-message-ttl、x-expires、x-max-length、x-maxlength-bytes、x-dead-letter-exchange、x-dead-letter-routing-key、x-max-priority
         */
        channel.queueDeclare("work_queue", true, false, false, null);

        //5. 接收消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             * 回调方法,当收到消息后,会自动执行该方法
             * void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
             * 参数:
             * (1)String consumerTag:标识
             * (2)Envelope envelope:获取一些信息,交换机,路由key...
             * (3)AMQP.BasicProperties properties:配置信息
             * (4)byte[] body:数据
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
//                System.out.println("consumerTag:" + consumerTag);
//                System.out.println("Exchange:" + envelope.getExchange());
//                System.out.println("RoutingKey:" + envelope.getRoutingKey());
//                System.out.println("properties:" + properties);
                System.out.println("body:" + new String(body));
            }
        };
        /**
         * 【API说明】:
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数:
         * (1)String queue:队列名称
         * (2)boolean autoAck:是否自动确认
         * (3)Consumer callback:回调对象
         */
        channel.basicConsume("work_queue", true, consumer);

        //6.关闭资源(消费者需要监听生产者消息,这里不关闭)

    }

}

三、测试

3.1、单条消息测试

(1)先启动消费者类1、消费者类2,消费监听生产者消息。

(2)再启动生产者类生产消息,消费者消息消息,即控制台输出:

说明: 在一个队列中如果有多个消费者,那么消费者之间对于同一个消息的关系是 竞争 的关系。

所以只有一个消费者类消费了消息:

RabbitMQ消息中间件(三):工作模式之工作队列(Work queues)_第2张图片
RabbitMQ消息中间件(三):工作模式之工作队列(Work queues)_第3张图片


3.2、多条消息测试

修改生产者类代码,循环生产10条消息:

String bodyMsg = "hello rabbitmq~~~好的";
// channel.basicPublish("", "helloworld_queue", null, bodyMsg.getBytes());
for (int i = 0; i < 10; i++) {
    channel.basicPublish("", "work_queue", null, ("【" + i + "】" + bodyMsg).getBytes());
}

(1)先启动消费者类1、消费者类2,消费监听生产者消息。

(2)再启动生产者类生产消息,消费者消息消息,即控制台输出:

说明: 在一个队列中如果有多个消费者,那么消费者之间对于同一个消息的关系是 竞争 的关系。

所以两个消费者类竞争消费了10消息:
RabbitMQ消息中间件(三):工作模式之工作队列(Work queues)_第4张图片
RabbitMQ消息中间件(三):工作模式之工作队列(Work queues)_第5张图片


四、小结

(1)在一个队列中如果有多个消费者,那么消费者之间对于同一个消息的关系是竞争的关系。

(2)Work Queues 对于任务过重或任务较多情况使用工作队列可以提高任务处理的速度。例如:短信服务部署多个,只需要有一个节点成功发送即可。


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