RabbitMQ 教程 - "Hello World!"
简介
先决条件
本教程假设 RabbitMQ 已 安装 并在 localhost 上的 标准端口 (5672) 上运行。如果您使用不同的主机、端口或凭据,则需要调整连接设置。
哪里寻求帮助
如果您在学习本教程时遇到困难,可以通过 GitHub Discussions 或 RabbitMQ 社区 Discord 联系我们。
RabbitMQ 是一个消息代理:它接收并转发消息。你可以把它想象成一个邮局:当你把想要寄出的邮件放进邮箱时,你可以确信邮递员最终会将邮件送到你的收件人手中。在这个比喻中,RabbitMQ 就是邮箱、邮局和邮递员。
RabbitMQ 和邮局的主要区别在于,它不处理纸张,而是接收、存储和转发数据的二进制数据块——消息。
RabbitMQ 和消息传递通常会使用一些行话。
-
生产(Producing)指的仅仅是发送。发送消息的程序就是生产者(producer)。
-
队列 是 RabbitMQ 中邮箱的名称。虽然消息在 RabbitMQ 和你的应用程序之间流动,但它们只能存储在队列 中。队列 的大小仅受主机内存和磁盘空间的限制,它本质上是一个大的消息缓冲区。
许多生产者 可以发送消息到同一个队列,许多消费者 可以尝试从同一个队列 接收数据。
这就是我们表示队列的方式
-
消费 的含义与接收类似。消费者 是一个主要等待接收消息的程序。
请注意,生产者、消费者和代理不一定需要驻留在同一台主机上;事实上,在大多数应用程序中它们都不会。一个应用程序也可以同时是生产者和消费者。
"Hello World"
(使用 Kotlin 客户端)
在本教程的这一部分,我们将用 Kotlin 编写两个程序:一个发送单条消息的生产者,以及一个接收并打印消息的消费者。我们将略过 Kotlin API 的一些细节,集中精力完成这个非常简单的入门示例。这就是消息传递领域的“Hello World”。
在下面的图表中,“P”是我们的生产者,“C”是我们的消费者。中间的框是一个队列——RabbitMQ 代表消费者存储的消息缓冲区。
Kotlin 客户端库
RabbitMQ 支持多种协议。本教程使用 AMQP 0-9-1,这是一种开放的通用消息传递协议。RabbitMQ 有许多不同语言的客户端。我们将使用适用于 Kotlin 的 Kourier 客户端库。
Kourier 是一个现代的、基于 Kotlin 协程的 AMQP 0-9-1 客户端。要在您的项目中使用它,请添加以下依赖项
Gradle (Kotlin DSL)
dependencies {implementation("dev.kourier:amqp-client:x.x.x")}Gradle (Groovy DSL)
dependencies {implementation 'dev.kourier:amqp-client:x.x.x'}Maven
<dependency><groupId>dev.kourier</groupId><artifactId>amqp-client-jvm</artifactId><version>x.x.x</version></dependency>我们建议查看 Kourier 发布页面以获取最新的版本号,并将上文中的
x.x.x替换为最新的稳定版本。
现在我们已经设置好了 Kotlin 客户端库,可以开始编写代码了。
发送
我们将消息发布者(发送方)称为 send,将消息消费者(接收方)称为 receive。发布者将连接到 RabbitMQ,发送一条消息,然后退出。
我们需要引入一些依赖
import dev.kourier.amqp.Field
import dev.kourier.amqp.Properties
import dev.kourier.amqp.connection.amqpConfig
import dev.kourier.amqp.connection.createAMQPConnection
import kotlinx.coroutines.CoroutineScope
设置发送函数和队列名称
val queueName = "hello"
suspend fun send(coroutineScope: CoroutineScope) {
// ...
}
然后我们可以创建与服务器的连接
suspend fun send(coroutineScope: CoroutineScope) {
val config = amqpConfig {
server {
host = "localhost"
}
}
val connection = createAMQPConnection(coroutineScope, config)
val channel = connection.openChannel()
// Publishing code will go here...
channel.close()
connection.close()
}
连接抽象了套接字连接,并为我们处理了协议版本协商、身份验证等工作。此处我们连接的是本地机器上的 RabbitMQ 节点,因此使用了 localhost。如果我们要连接到另一台机器上的节点,只需在此处指定其主机名或 IP 地址即可。
接下来我们创建一个通道(channel),这是实现大部分 API 功能的地方。
为了发送,我们必须声明一个要发送到的队列;然后我们可以将消息发布到该队列。
channel.queueDeclare(
queueName,
durable = true,
exclusive = false,
autoDelete = false,
arguments = mapOf("x-queue-type" to Field.LongString("quorum"))
)
val message = "Hello World!"
channel.basicPublish(
message.toByteArray(),
exchange = "",
routingKey = queueName,
properties = Properties()
)
println(" [x] Sent '$message'")
声明队列是幂等的——只有在队列不存在时才会创建。消息内容是字节数组,因此您可以对其进行任意编码。
发送不起作用!
如果这是您第一次使用 RabbitMQ,但没有看到“Sent”消息,您可能会感到困惑,不知道哪里出了问题。也许代理启动时磁盘空间不足(默认需要至少 50 MB 可用空间),因此拒绝接收消息。检查代理的日志文件,看看是否有资源警报已记录,并在必要时降低可用磁盘空间阈值。配置指南将展示如何设置
disk_free_limit。
接收
我们的发布者就到这里了。我们的消费者会监听来自 RabbitMQ 的消息,所以与只发布一条消息的发布者不同,我们将保持消费者的运行状态,监听并打印消息。
设置与发布者相同;我们打开一个连接和一个通道,并声明我们将要消费的队列。注意这与 send 发布到的队列相匹配。
suspend fun receive(coroutineScope: CoroutineScope) {
val config = amqpConfig {
server {
host = "localhost"
}
}
val connection = createAMQPConnection(coroutineScope, config)
val channel = connection.openChannel()
channel.queueDeclare(
queueName,
durable = true,
exclusive = false,
autoDelete = false,
arguments = mapOf("x-queue-type" to Field.LongString("quorum"))
)
println(" [*] Waiting for messages. To exit press CTRL+C")
// Consuming code will go here...
channel.close()
connection.close()
}
请注意,我们在这里也声明了队列。因为我们可能在发布者之前启动消费者,所以我们希望确保在尝试从队列中消费消息之前,队列已经存在。
我们准备告诉服务器从队列中向我们发送消息。由于 Kourier 是基于 Kotlin 协程构建的,消费消息就像遍历通道(channel)一样简单
val consumer = channel.basicConsume(queueName, noAck = true)
for (delivery in consumer) {
val message = delivery.message.body.decodeToString()
println(" [x] Received '$message'")
}
总而言之
您可以将这两个函数包装在带有 runBlocking 代码块的 main 函数中
import dev.kourier.amqp.Field
import dev.kourier.amqp.Properties
import dev.kourier.amqp.connection.amqpConfig
import dev.kourier.amqp.connection.createAMQPConnection
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
val queueName = "hello"
suspend fun send(coroutineScope: CoroutineScope) {
val config = amqpConfig {
server {
host = "localhost"
}
}
val connection = createAMQPConnection(coroutineScope, config)
val channel = connection.openChannel()
channel.queueDeclare(
queueName,
durable = true,
exclusive = false,
autoDelete = false,
arguments = mapOf("x-queue-type" to Field.LongString("quorum"))
)
val message = "Hello World!"
channel.basicPublish(
message.toByteArray(),
exchange = "",
routingKey = queueName,
properties = Properties()
)
println(" [x] Sent '$message'")
channel.close()
connection.close()
}
suspend fun receive(coroutineScope: CoroutineScope) {
val config = amqpConfig {
server {
host = "localhost"
}
}
val connection = createAMQPConnection(coroutineScope, config)
val channel = connection.openChannel()
channel.queueDeclare(
queueName,
durable = true,
exclusive = false,
autoDelete = false,
arguments = mapOf("x-queue-type" to Field.LongString("quorum"))
)
println(" [*] Waiting for messages. To exit press CTRL+C")
val consumer = channel.basicConsume(queueName, noAck = true)
for (delivery in consumer) {
val message = delivery.message.body.decodeToString()
println(" [x] Received '$message'")
}
channel.close()
connection.close()
}
fun main() = runBlocking {
launch { send(this) }
launch { receive(this) }
delay(Long.MAX_VALUE) // Keep the main thread alive
}
消费者将打印它通过 RabbitMQ 从发布者那里收到的消息。消费者将持续运行,等待消息(使用 Ctrl-C 停止它)。
列出队列
您可能希望查看 RabbitMQ 有哪些队列以及其中有多少消息。您可以使用
rabbitmqctl工具(作为特权用户)来完成此操作。sudo rabbitmqctl list_queues在 Windows 上,省略 sudo。
rabbitmqctl.bat list_queues
接下来进入第二部分,构建一个简单的工作队列(work queue)。