RabbitMQ(五)之快速编写Hello RabbitMQ
程序员文章站
2022-06-27 20:30:40
一、搭建项目创建Maven项目导入rabbitmq包 <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId>...
一、搭建项目
创建Maven项目
导入rabbitmq包
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.6.5</version>
</dependency>
二、代码
生产者代码
public static void main(String[] args) {
//1、 创建连接工厂
ConnectionFactory connectionFactory = new ConnectionFactory();
// RabbitMQ服务IP
connectionFactory.setHost("127.0.0.1");
// RabbitMQ服务端口
connectionFactory.setPort(5672);
// 选择VirtualHost
connectionFactory.setVirtualHost("/");
Connection connection;
Channel channel=null;
try {
//2、 通过工厂创建连接
connection = connectionFactory.newConnection();
//3、通过连接创建Channel
channel = connection.createChannel();
String exchange = "";
String routingKey = "te01";
AMQP.BasicProperties basicProperties = null;
for (int i = 0; i < 5; i++) {
String body = "Producer:"+i;
//发送消息
channel.basicPublish(exchange, routingKey, basicProperties, body.getBytes());
}
// 按顺序关闭连接
channel.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
消费者代码
public static void main(String[] args) {
//1、 创建连接工厂
ConnectionFactory connectionFactory = new ConnectionFactory();
// RabbitMQ服务IP
connectionFactory.setHost("127.0.0.1");
// RabbitMQ服务端口
connectionFactory.setPort(5672);
// 选择VirtualHost
connectionFactory.setVirtualHost("/");
try {
//2、 通过工厂创建连接
Connection connection = connectionFactory.newConnection();
//3、通过连接创建Channel
Channel channel = connection.createChannel();
//4、创建队列
String queueName="te01";//队列名称
channel.queueDeclare(queueName, true, false, false, null);
//5、创建消费者
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
//6、配置channel
channel.basicConsume(queueName,true,queueingConsumer);
while (true){
QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
String body = new String(delivery.getBody());
System.out.println("消费者:"+body);
}
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
三、查看控制界面
进入界面:http://127.0.0.1:15672
执行生产者代码,查看控制面板发送消息队列里面有10条消息
执行消费者代码,控制台则会打印出消息列队里面的消息,再次查看控制台消息列队则为0。
本文地址:https://blog.csdn.net/qq_36306590/article/details/85949357