Java连接rabbitMQ(三步超简单)

rabbitMQ安装教程网上特别多就不多赘述,这里主要说一下怎么去连接

第一步,创建工程添加依赖

创建一个Maven项目,打开pom.xml,添加两个依赖,并更新Maven。

<?xml version="1.0" encoding="UTF-8"?>
<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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>rabbitMQdemo</artifactId>
    <version>1.0-SNAPSHOT</version>

------------添加下面两个依赖------------

    <dependencies>
        <dependency>
            <groupId>com.rabbitmq</groupId>
            <artifactId>amqp-client</artifactId>
            <version>5.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.25</version>
        </dependency>
    </dependencies>

</project>

第二步,配置连接

在src->main->java中新建一个文件夹utils,在此文件夹中添加class:rabbitMQUtils

package utils;

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

public class RabbitMQUtils {

    private static final ConnectionFactory factory;

    static {
        factory = new ConnectionFactory();
        factory.setHost("126.239.25.24");  // 换成自己的ip
        factory.setPort(5672);  // 一般默认端口为5672
        factory.setUsername("root");  
        factory.setPassword("123456");
        factory.setAutomaticRecoveryEnabled(true);  // 开启Connection自动恢复功能
        factory.setNetworkRecoveryInterval(5000);
        factory.setVirtualHost("/");
        factory.setConnectionTimeout(30 * 1000);
        factory.setHandshakeTimeout(30 * 1000);
        factory.setShutdownTimeout(0);
    }

    // 定义提供连接对象的方法
    public static Connection getConnection() {
        try {
            return factory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 定义关闭通道和连接的方法
    public static void closeAll(Channel chan, Connection conn) {
        try{
            if(chan != null)  chan.close();
            if(conn != null)  conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

需要注意的是要将ip、用户名、密码更换成自己的,如果是在服务器上装的MQ记得在安全组中把端口放行,另外记得设置虚拟用户"/",或改成自己的虚拟用户名。

第三步,测试连接

使用直连测试连接效果,在src->main->java创建文件夹direct,添加两个class:consumer和producer。

package direct;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;
import java.io.IOException;

public class producer {

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

        Connection connection = RabbitMQUtils.getConnection();
        assert connection != null;
        final Channel channel = connection.createChannel();

        // 声明交换机
        channel.exchangeDeclare("direct_router", "direct", true, false, false, null);

        // 声明消息队列
        // 参数1: 队列名称
        // 参数2: 定义是否需要持久化队列,true为持久化
        // 参数3: 定义是否让当前连接独占队列,true为独占
        // 参数4: 是否在消费完成后自动删除队列,true为删除
        // 参数5: 额外附加参数,传入HashMap<String, Object>
        channel.queueDeclare("direct_queue", false, false, false, null);

        // 交换机与消息队列绑定
        channel.queueBind("direct_queue", "direct_router", "Dir-RQ");

        // 发送消息
        // 参数1: 交换机名称
        // 参数2: routingKey
        // 参数3: 若为true,则当消息无法送达指定队列时会触发channel.BasicReturn事件否则broker会将消息直接丢弃
        // 参数4: 传递消息的额外设置
        // 参数5: 发送消息内容
        String msg="direct producer message";
        channel.basicPublish("direct_router", "Dir-RQ", true, null, msg.getBytes());

        RabbitMQUtils.closeAll(channel, connection);
    }
}
package direct;

import com.rabbitmq.client.*;
import utils.RabbitMQUtils;
import java.io.IOException;

public class consumer {

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

        Connection connection = RabbitMQUtils.getConnection();
        assert connection != null;
        final Channel channel = connection.createChannel();

        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(
                    String consumerTag,
                    Envelope envelope,
                    AMQP.BasicProperties properties,
                    byte[] body
            ) throws IOException {

                // 打印消息
                String msg= new String(body, "utf-8");
                System.out.println(msg);

                // 应答机制 将队列中的消息删除掉,第二个参数为是否需要确认多个ACK
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        // 接收消息
        // 参数1: 队列名称
        // 参数2: 是否自动签收消息,对应上面的应答机制,最好手动删,否则消费者多了可能会出问题
        channel.basicConsume("direct_queue", false, "ConsumerTag", consumer);

        Thread.sleep(20000);
        RabbitMQUtils.closeAll(channel, connection);
    }
}

右键运行consumer,20s内运行producer就能看见控制台中接收到了producer发出的消息。

下面是接收字符串、对象、对象列表的示例代码,主要是序列化。

public class TaskProcessing {
    private final String queueName;
    private final String consumerTag;

    public TaskProcessing(String queueName, String consumerTag) {
        this.queueName = queueName;
        this.consumerTag = consumerTag;
    }

    public void listening() {
        try {
            Connection connection = RabbitMQUtils.getConnection();
            if (connection != null) {
                Channel channel = connection.createChannel();
                channel.queueDeclare(queueName, true, false, false, null);
                System.out.println("Waiting for messages. To exit press CTRL+F2");

                DefaultConsumer consumer = new DefaultConsumer(channel) {
                    @Override
                    public void handleDelivery(
                            String consumerTag,
                            Envelope envelope,
                            AMQP.BasicProperties properties,
                            byte[] body
                    ) {
                        try {
                            // 打印消息
                            String msg = new String(body, StandardCharsets.UTF_8);
                            System.out.println(consumerTag + msg + "'");
                            // 工作代码
                            channel.basicAck(envelope.getDeliveryTag(), false);
                        } catch (IOException e) {
                            // 数据异常
                            System.err.println("Failed to acknowledge message: " + e.getMessage());
                        }
                    }
                };
                channel.basicConsume(queueName, false, consumerTag, consumer);
            }
        } catch (IOException e) {
            // 获取连接或通道创建失败异常
            System.err.println("Error in setting up the connection or channel: " + e.getMessage());
        }
    }

    public void listeningIndividual() {
        try {
            Connection connection = RabbitMQUtils.getConnection();
            if (connection != null) {
                Channel channel = connection.createChannel();
                channel.queueDeclare(queueName, true, false, false, null);
                channel.basicQos(1);
                System.out.println("Waiting for messages. To exit press CTRL+F2");

                ObjectMapper objectMapper = new ObjectMapper();

                DefaultConsumer consumer = new DefaultConsumer(channel) {
                    @Override
                    public void handleDelivery(
                            String consumerTag,
                            Envelope envelope,
                            AMQP.BasicProperties properties,
                            byte[] body
                    ) {
                        try {
                            Individual individual = objectMapper.readValue(body, Individual.class);
                            // 打印消息
                            System.out.println(consumerTag + individual.getResourceUtilization() + "'");
                            // 工作代码
                            channel.basicAck(envelope.getDeliveryTag(), false);
                        } catch (IOException e) {
                            // 数据异常
                            System.err.println("Failed to acknowledge message: " + e.getMessage());
                        }
                    }
                };
                channel.basicConsume(queueName, false, consumerTag, consumer);
            }
        } catch (IOException e) {
            // 获取连接或通道创建失败异常
            System.err.println("Error in setting up the connection or channel: " + e.getMessage());
        }
    }

    public void listeningIndividualList() {
        try {
            Connection connection = RabbitMQUtils.getConnection();
            if (connection != null) {
                Channel channel = connection.createChannel();
                channel.queueDeclare(queueName, true, false, false, null);
                channel.basicQos(1);
                System.out.println("Waiting for messages. To exit press CTRL+F2");

                ObjectMapper objectMapper = new ObjectMapper();

                DefaultConsumer consumer = new DefaultConsumer(channel) {
                    @Override
                    public void handleDelivery(
                            String consumerTag,
                            Envelope envelope,
                            AMQP.BasicProperties properties,
                            byte[] body
                    ) {
                        try {
                            List<Individual> individuals = objectMapper.readValue(body, new TypeReference<List<Individual>>() {});
                            // 打印消息
                            for(Individual individual : individuals) {
                                System.out.println(consumerTag +"接收:"+ individual.getResourceUtilization() + "'");
                            }
                            // 工作代码
                            channel.basicAck(envelope.getDeliveryTag(), false);
                        } catch (IOException e) {
                            // 数据异常
                            System.err.println("Failed to acknowledge message: " + e.getMessage());
                        }
                    }
                };
                channel.basicConsume(queueName, false, consumerTag, consumer);
            }
        } catch (IOException e) {
            // 获取连接或通道创建失败异常
            System.err.println("Error in setting up the connection or channel: " + e.getMessage());
        }
    }

对应的发送代码

public void send(List<String> tasks) {
        try {
            Connection connection = RabbitMQUtils.getConnection();
            if(connection != null) {
                // 声明交换机
                Channel channel = connection.createChannel();
                channel.exchangeDeclare(exchangeName, "direct", true, false, false, null);
                // 声明队列
                channel.queueDeclare(queueName, true, false, false, null);
                // 交换机与消息队列绑定
                channel.queueBind(queueName, exchangeName, routingKey);
                for(String task : tasks) {
                    channel.basicPublish(exchangeName, routingKey, true, null, task.getBytes());
                }
                RabbitMQUtils.closeAll(channel, connection);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendIndividual(Individual individual) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Connection connection = RabbitMQUtils.getConnection();
            if(connection != null) {
                Channel channel = connection.createChannel();
                channel.exchangeDeclare(exchangeName, "direct", true, false, false, null);
                channel.queueDeclare(queueName, true, false, false, null);
                channel.queueBind(queueName, exchangeName, routingKey);

                byte[] messageBody = objectMapper.writeValueAsBytes(individual);
                channel.basicPublish(exchangeName, routingKey, true, null, messageBody);

                RabbitMQUtils.closeAll(channel, connection);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendIndividualList(List<Individual> individuals) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Connection connection = RabbitMQUtils.getConnection();
            if(connection != null) {
                Channel channel = connection.createChannel();
                channel.exchangeDeclare(exchangeName, "direct", true, false, false, null);
                channel.queueDeclare(queueName, true, false, false, null);
                channel.queueBind(queueName, exchangeName, routingKey);

                byte[] messageBody = objectMapper.writeValueAsBytes(individuals);
                channel.basicPublish(exchangeName, routingKey, true, null, messageBody);

                RabbitMQUtils.closeAll(channel, connection);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java连接RabbitMQ,您可以使用RabbitMQ的官方Java客户端库,即RabbitMQ Java Client。以下是一个简单的示例代码,演示如何连接RabbitMQ服务器: 首先,确保您已经将RabbitMQJava客户端库添加到您的项目中。您可以在 Maven 或 Gradle 中添加以下依赖项: Maven 依赖项: ```xml <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.9.0</version> </dependency> ``` Gradle 依赖项: ```groovy implementation 'com.rabbitmq:amqp-client:5.9.0' ``` 然后,您可以使用以下代码连接RabbitMQ: ```java import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; public class RabbitMQConnection { public static void main(String[] args) { // 创建连接工厂 ConnectionFactory factory = new ConnectionFactory(); // 配置 RabbitMQ 服务器连接信息 factory.setHost("localhost"); // RabbitMQ 服务器地址 factory.setPort(5672); // RabbitMQ 服务器端口号 factory.setUsername("guest"); // RabbitMQ 用户名 factory.setPassword("guest"); // RabbitMQ 密码 try { // 创建连接 Connection connection = factory.newConnection(); // 连接成功后可进行其他操作,例如创建/消费队列等 System.out.println("成功连接RabbitMQ 服务器"); // 关闭连接 connection.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 请确保将上述代码中的 RabbitMQ 服务器地址、端口号、用户名和密码更改为您实际使用的值。这段代码将尝试连接RabbitMQ 服务器并打印成功连接的消息。如果连接失败,将打印出异常信息。 这只是一个简单的示例,您可以根据您的实际需求进行更多的操作,例如创建队列、发送/接收消息等。有关更多详细信息,请参阅 RabbitMQ Java Client 的文档。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值