JAVA操作RabbitMQ-work工作队列模式

 工作队列模式:一个生产者,多个消费者,多个消费者共同监听一个队列,一个消息只能被一个消费者获取。 工作队列模式又分为两种,轮询模式分发和公平分发。

轮询模式分发:一条消息一个消费者,按均分配。

公平分发:根据消费者的消费能力进行公平分发,处理快的处理的多,处理慢的处理的少;按劳分配。

P:消息的生产者
C1,C2:消息的消费者
红色:队列

生产者将消息发送到队列(通过默认交换机),消费者从队列中获取消息。

 1. pom.xml引入rabbitmq依赖


     com.rabbitmq
     amqp-client
     5.13.1

2. 创建队列

public class CreateQueue {

    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 = null;
        Channel channel = null;
        try {
            // 创建连接Connection
            connection = connectionFactory.newConnection("生产者");
            // 创建channel
            channel = connection.createChannel();
            String queueName = "work-queue1";

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

        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 关闭channel和connection
            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. 消费者1

public class Consumer1 {

    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 = null;
        Channel channel = null;
        try {
            // 创建连接Connection
            connection = connectionFactory.newConnection("消费者1");
            // 创建channel
            channel = connection.createChannel();

            // 监听发送来的消息
            // 队列名称,是否自动确认消息,接收消息的回调,消费者取消时的回调
            channel.basicConsume("work-queue1", true,
                    (consumerTag, message) -> System.out.println("收到消息:" + new String(message.getBody(), StandardCharsets.UTF_8)),
                    consumerTag -> System.out.println("消费者取消订阅"));

            while (true) {
                //阻塞进程, 防止消费者程序退出
            }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 关闭channel和connection
            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();
                }
            }
        }


    }
}

4. 消费者2

public class Consumer2 {

    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 = null;
        Channel channel = null;
        try {
            // 创建连接Connection
            connection = connectionFactory.newConnection("消费者2");
            // 创建channel
            channel = connection.createChannel();

            // 监听发送来的消息
            // 队列名称,是否自动确认消息,接收消息的回调,消费者取消时的回调
            channel.basicConsume("work-queue1", true,
                    (consumerTag, message) -> System.out.println("收到消息:" + new String(message.getBody(), StandardCharsets.UTF_8)),
                    consumerTag -> System.out.println("消费者取消订阅"));

            while (true) {
                //阻塞进程, 防止消费者程序退出
            }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 关闭channel和connection
            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();
                }
            }
        }


    }
}

 5. 生产者

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 = null;
        Channel channel = null;
        try {
            // 创建连接Connection
            connection = connectionFactory.newConnection("生产者");
            // 创建channel
            channel = connection.createChannel();
            String queueName = "work-queue1";

            // 发送消息到队列
            for (int i = 0; i < 30; i++) {
                // exchange,routingKey, props,message body
                channel.basicPublish("", queueName, null, ("hello message" + i).getBytes(StandardCharsets.UTF_8));
            }

            System.out.println("消息发送成功");

        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 关闭channel和connection
            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();
                }
            }
        }
    }
}

6. 先创建队列,启动两个消费者,再启动生产者发送消息,你会看到两个消费者收到的消息个数都一样。以此可以看出一条消息一个消费者,按均分配,默认是轮询模式。

JAVA操作RabbitMQ-work工作队列模式_第1张图片

 7.公平分发,需要修改为手动ack,并且设置qos(实际使用要根据服务器配置来配置)

消费者1

public class Consumer1 {

    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 = null;
        Channel channel = null;
        try {
            // 创建连接Connection
            connection = connectionFactory.newConnection("消费者1");
            // 创建channel
            channel = connection.createChannel();

            // 监听发送来的消息
            // 队列名称,是否自动确认消息,接收消息的回调,消费者取消时的回调
            Channel finalChannel = channel;
            channel.basicQos(10);
            channel.basicConsume("work-queue1", false,
                    (consumerTag, message) -> {
                        System.out.println("收到消息:" + new String(message.getBody(), StandardCharsets.UTF_8));
                        finalChannel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                    },
                    consumerTag -> System.out.println("消费者取消订阅"));

            while (true) {
                //阻塞进程, 防止消费者程序退出
            }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 关闭channel和connection
            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();
                }
            }
        }


    }
}

消费者2

public class Consumer2 {

    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 = null;
        Channel channel = null;
        try {
            // 创建连接Connection
            connection = connectionFactory.newConnection("消费者2");
            // 创建channel
            channel = connection.createChannel();

            // 监听发送来的消息
            // 队列名称,是否自动确认消息,接收消息的回调,消费者取消时的回调
            Channel finalChannel = channel;
            channel.basicQos(5);
            channel.basicConsume("work-queue1", false,
                    (consumerTag, message) ->{
                        System.out.println("收到消息:" + new String(message.getBody(), StandardCharsets.UTF_8));
                        finalChannel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                    },
                    consumerTag -> System.out.println("消费者取消订阅"));

            while (true) {
                //阻塞进程, 防止消费者程序退出
            }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 关闭channel和connection
            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();
                }
            }
        }


    }
}

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