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

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

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

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

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

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

 1. pom.xml引入rabbitmq依赖

<dependency>
     <groupId>com.rabbitmq</groupId>
     <artifactId>amqp-client</artifactId>
     <version>5.13.1</version>
</dependency>

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

 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();
                }
            }
        }


    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值