RabbitMQ--work queue(平均分发)

本文展示了如何在Java中使用RabbitMQ作为消息队列,包括引入依赖、创建RabbitMQUtil工具类、生产者和消费者的实现。通过RabbitMQUtil设置连接配置,生产者发送10条消息到队列,消费者监听并消费这些消息,实现了简单的消息传递功能。
摘要由CSDN通过智能技术生成

引入依赖

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

创建RabbitMQUtil

package utils;

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

/**
 * @auther gsj
 * @create 2021-04-29-17:24
 */
public class RabbitMQUtil {
    private  static ConnectionFactory connectionFactory;

    static{
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("8.140.5.231");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/gsj");
        connectionFactory.setUsername("gsj");
        connectionFactory.setPassword("gsj");

    }
    public static Connection getConnection(){
        try {
            return connectionFactory.newConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static void closeConnectionAndChanel(Channel channel,Connection connection){
        try {
            if (channel!=null)channel.close();
            if (connection!=null)connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

生产者

public class provider {
    public static void main(String[] args) throws IOException {
        Connection connection = RabbitMQUtil.getConnection();

            Channel channel = connection.createChannel();

            channel.queueDeclare("work",true,false,false,null);

            for (int i = 0; i < 10; i++) {
                channel.basicPublish("","work",null,(i + "hello").getBytes());
            }

            RabbitMQUtil.closeConnectionAndChanel(channel,connection);
    }
}

消费者1

public class Customer1 {
    public static void main(String[] args) throws IOException {

        Connection connection = RabbitMQUtil.getConnection();

        Channel channel = connection.createChannel();

        channel.queueDeclare("work",true,false,false,null);

        channel.basicConsume("work",true,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("消费者-1:"+new String(body));
            }
        });
    }
}

消费者2如上

运行结果
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值