Java中配置RabbitMQ基本步骤

在Java中配置RabbitMQ,需要遵循以下步骤:

1.添加依赖

在项目的pom.xml文件中添加RabbitMQ的Java客户端依赖:

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

2.创建连接工厂

创建一个连接工厂,用于创建与RabbitMQ服务器的连接:

import com.rabbitmq.client.ConnectionFactory;

public class RabbitMQConfig {

    public static ConnectionFactory createConnectionFactory() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost"); // 设置RabbitMQ服务器地址
        factory.setPort(5672); // 设置RabbitMQ服务器端口
        factory.setUsername("guest"); // 设置用户名
        factory.setPassword("guest"); // 设置密码
        return factory;
    }
}

3.创建生产者和消费者 

创建一个生产者,用于发送消息到RabbitMQ队列:

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

public class Producer {

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = RabbitMQConfig.createConnectionFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        String queueName = "test_queue";
        channel.queueDeclare(queueName, false, false, false, null);
        String message = "Hello, RabbitMQ!";
        channel.basicPublish("", queueName, null, message.getBytes("UTF-8"));
        System.out.println("Sent: '" + message + "'");

        channel.close();
        connection.close();
    }
}
创建一个消费者,用于从RabbitMQ队列中接收消息:4
import com.rabbitmq.client.*;

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

public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = RabbitMQConfig.createConnectionFactory();
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        String queueName = "test_queue";
        channel.queueDeclare(queueName, false, false, false, null);
        System.out.println("Waiting for messages...");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println("Received: '" + message + "'");
        };
        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
    }
}

4.运行生产者和消费者 

分别运行Producer和Consumer类的main方法,生产者将消息发送到RabbitMQ队列,消费者将从队列中接收并处理消息。