用java实现rabbitmq
时间: 2023-05-26 22:01:57 浏览: 162
java使用rabbitMq服务
1. 安装RabbitMQ
首先需要去RabbitMQ官网下载二进制引擎,安装后就可以启动RabbitMQ了。如果在Linux机器上安装RabbitMQ,以下是启动RabbitMQ服务的命令。
sudo apt-get install rabbitmq-server
sudo service rabbitmq-server start
2. 引入RabbitMQ依赖
使用Java代码连接RabbitMQ的第一步是在你的项目中引用RabbitMQ依赖。以下是Maven依赖:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>x.x.x</version>
</dependency>
3. 编写一个生产者
在这个示例中,我们将创建一个生产者,它将向RabbitMQ发送消息。以下是生产者的代码:
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Producer {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws IOException, TimeoutException {
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 World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
}
}
}
4. 编写一个消费者
在这个示例中,我们将创建一个消费者,它将从RabbitMQ接收消息。以下代码是消费者:
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Recv {
private static final String QUEUE_NAME = "hello";
public static void main(String[] argv) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
运行生产者,然后运行一个或多个消费者,他们将从RabbitMQ接收消息。至此,使用Java实现RabbitMQ就完成了。
阅读全文