RabbitMQ快速入门
程序员文章站
2022-05-03 22:11:19
...
快速入门-消息生产与消费(即生产者把消息放到消息队列,然后消费者直接去消息队列取消息进行消费)
ConnectionFactory:获取连接工厂
Connection:一个链接
Channel:数据通信通道,课发送和接收消息
Queue:具体的消息存储队列
Producer & Consumer:生产和消费者
导入所需pom依赖:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>3.6.5</version>
</dependency>
消费端代码:
package com.ue.quickstart;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
/**
* 消费端
* @Author LiJun
* @Date 2020/02/14
* @Time 18:46
*/
public class Consumer {
public static void main(String[] args) throws Exception {
//1、创建一个ConnectionFactory, 并进行配置
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.14.758");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2、通过连接工厂创建连接
Connection connection = connectionFactory.newConnection();
//3、通过connection创建一个Channel
Channel channel = connection.createChannel();
//4、声明(创建)一个队列
String queueName = "test001";
//参数:队列名称、持久化与否、独占与否、无消息队列是否自动删除、消息参数
//queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
channel.queueDeclare(queueName, true, false, false, null);
//5、创建消费者
QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
//6、设置Channel
//参数:队列名称、自动签收、消费者回调
//basicConsume(String queue, boolean autoAck, Consumer callback)
channel.basicConsume(queueName, true, queueingConsumer);
while(true){
//7、获取消息(Delivery:传送)
QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
String msg = new String(delivery.getBody());
System.err.println("消费端: " + msg);
//Envelope envelope = delivery.getEnvelope();
}
}
}
生产端代码:
package com.ue.quickstart;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
* 生产端
* @Author LiJun
* @Date 2020/02/14
* @Time 18:49
*/
public class Procuder {
public static void main(String[] args) throws Exception {
//1、创建一个ConnectionFactory, 并进行配置
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.14.758");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2、通过连接工厂创建连接
Connection connection = connectionFactory.newConnection();
//3、通过connection创建一个Channel
Channel channel = connection.createChannel();
//4、通过Channel发送数据
for(int i=0; i < 5; i++){
String msg = "Hello RabbitMQ!";
//1、exchange 2、routingKey
channel.basicPublish("", "test001", null, msg.getBytes());
}
//5、记得要关闭相关的连接
channel.close();
connection.close();
}
}
注意先运行消费者,再运行生产者
打印结果如下:
本例中并没有指定交换机,所以会使用RabbitMQ默认的交换机
上一篇: 【分布式】全局唯一ID生成策略
下一篇: RabbitMQ快速入门