java生产消费rabbitmq

小小编辑 1年前 ⋅ 142 阅读

下面是一个简单的Java代码示例,包含生产者和消费者,以及相应的Maven POM文件来实现RabbitMQ的生产和消费: Java代码示例:

// 生产者 import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Connection; import com.rabbitmq.client.Channel;

public class RabbitMQProducer { private final static String QUEUE_NAME = "hello";

public static void main(String[] args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");

    try (Connection connection = factory.newConnection();
         Channel channel = connection.createChannel()) {
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello RabbitMQ!";
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println("Sent: " + message);
    }
}

}

// 消费者 import com.rabbitmq.client.*;

public class RabbitMQConsumer { private final static String QUEUE_NAME = "hello";

public static void main(String[] args) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");

    try (Connection connection = factory.newConnection();
         Channel channel = connection.createChannel()) {
        channel.queueDeclare(QUEUE_NAME, 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(QUEUE_NAME, true, deliverCallback, consumerTag -> {});
    }
}

} Maven POM文件:

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

在上面的示例中,我们创建了一个名为 rabbitmq-example 的Maven项目。在POM文件中,我们添加了RabbitMQ客户端的依赖,以便在代码中使用RabbitMQ相关的类和接口。根据你使用的RabbitMQ客户端版本,你可能需要更改amqp-client的版本号。

请注意,为了使代码正常运行,确保你已经在本地运行了RabbitMQ代理,且与代码中设置的主机名(localhost)相匹配。