RabbitMQ和一般的消息传递使用的术语
- 发送消息的程序是
生产者
队列
是RabbitMQ内部的邮箱的名称
尽管消息流经RabbitMQ和您的应用程序,但它们只能存储在队列
中
许多生产者可以将消息发送到一个队列,许多消费者可以尝试从一个队列接收数据
。
- 一个消费者是一个程序,主要是
等待接收信息
:
一、HelloWorld
在该案例中,主要包括发送单个消息的生产者
和接收消息并打印出来的消费者
如下图,P
是我们的生产者,C
是我们的消费者。
中间的框
是一个队列-RabbitMQ代表使用者保留的消息缓冲区
1.1、添加maven依赖
<!-- https://mvnrepository.com/artifact/com.rabbitmq/amqp-client -->
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.10.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.22</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.30</version>
</dependency>
1.2、provider类
package com.op.test;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.nio.charset.StandardCharsets;
public class Provider {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.17.129"); //设置主机地址
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 + "'");
}
}
}
1.3、Consumer类
package com.op.test;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
public class Consumer {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.17.129");
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 -> { });
}
}
运行结果
以上的案例建立在生产着发送消息,消费者接收消息的过程,在一个通道下进行。