RabbitMQ 简单队列
★简单队列
官网:https://www.rabbitmq.com/getstarted.html
消息生产者(producer):只是用来发送.
队列(Queue):用来存储消息的,队列不限制大小,取决于服务器内存和硬盘的大小。
消费者(Consumer):用来监听队列、接收消息的
1.IDEA创建一个新的Maven项目
下一步:
2.添加依赖(在Maven仓库中搜索 RabbitMQ Java Client)
<!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client --> <dependency> <groupId>com.rabbitmq</groupId> <artifactId>amqp-client</artifactId> <version>5.10.0</version> </dependency>
编写Send.java代码:
package com.ckfuture.simple.send;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.nio.charset.StandardCharsets;
/**
* 简单队列-消息生产者
*/
public class Send {
//定义队列名称
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) 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 World!";
//发送消息
channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
System.out.println(" [x] Sent '" + message + "'");
}
}
}
运行结果:
在管理控制台可以看到:
点击进入详情:
编写Recv.java代码:
package com.ckfuture.simple.recv; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.DeliverCallback; /** * 简单队列-消息消费者 */ public class Recv { private final static String QUEUE_NAME = "hello"; public static void main(String[] argv) throws Exception { //创建连接工厂 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 -> { }); } }
查看运行结果:
在管理后台查看:
进入详情后,消息已经被获取。
在信道(channels)中可以查看监听的消费者