跳至主内容

RabbitMQ 教程 - 路由

路由

(使用 Kotlin 客户端)

信息

先决条件

本教程假设 RabbitMQ 已 安装 并在 localhost 上的 标准端口 (5672) 上运行。如果您使用不同的主机、端口或凭据,则需要调整连接设置。

哪里寻求帮助

如果您在学习本教程时遇到困难,可以通过 GitHub DiscussionsRabbitMQ 社区 Discord 联系我们。

上一篇教程中,我们构建了一个简单的日志系统。我们能够将日志消息广播给多个接收者。

在本教程中,我们将为其添加一项功能——我们将能够仅订阅一部分消息。例如,我们可以将仅关键错误消息定向到日志文件(以节省磁盘空间),同时仍然能够将所有日志消息打印到控制台。

绑定

在之前的示例中,我们已经创建了绑定。您可能还记得这样的代码

channel.queueBind(queueName, "logs", routingKey = "")

绑定是交换机和队列之间的关系。这可以简单地理解为:队列对来自此交换机的消息感兴趣。

绑定可以接受一个额外的 routingKey 参数。为了避免与 basicPublish 的参数混淆,我们将称其为 绑定键 (binding key)。这就是我们如何使用键来创建绑定的方法

channel.queueBind(queueName, "direct_logs", routingKey = "black")

绑定 key 的含义取决于交换机类型。我们之前使用的 fanout 交换机只是忽略了它的值。

直连交换机

我们在上一篇教程中构建的日志系统会将所有消息广播给所有消费者。我们希望对其进行扩展,以允许根据消息的严重程度来过滤消息。例如,我们可能希望将日志消息写入磁盘的程序只接收严重错误,而不是在警告或信息日志消息上浪费磁盘空间。

我们使用的是fanout交换,这并没有给我们太大的灵活性——它只能进行无差别的广播。

我们将改用 direct 交换机。direct 交换机背后的路由算法很简单——消息会被发送到其 binding key 精确匹配消息的 routing key 的队列。

为了说明这一点,请考虑以下设置

在此设置中,我们可以看到 direct 交换机 X 绑定了两个队列。第一个队列绑定了绑定 key orange,第二个队列有两个绑定,一个绑定 key 是 black,另一个是 green

在这种设置下,发布到具有路由 key orange 的交换机的消息将被路由到队列 Q1。具有路由 key blackgreen 的消息将发送到 Q2。所有其他消息将被丢弃。

多个绑定

使用相同的绑定 key 绑定多个队列是完全合法的。在我们的示例中,我们可以添加一个 XQ1 之间的绑定,绑定 key 为 black。在这种情况下,direct 交换机将表现得像 fanout,并将消息广播给所有匹配的队列。路由 key 为 black 的消息将被传递给 Q1Q2

发送日志

我们将把这种模型用于我们的日志系统。我们将不再使用 fanout,而是将消息发送到 direct 交换机。我们将提供日志严重程度作为 routing key。这样,接收程序就能够选择它想要接收的严重程度。让我们先专注于发送日志。

一如既往,我们需要先创建一个交换

channel.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT)

我们已准备好发送消息

channel.basicPublish(
message.toByteArray(),
exchange = "direct_logs",
routingKey = severity,
properties = Properties()
)

为了简化,我们将假设“严重性”可以是 infowarningerror 之一。

订阅

接收消息的工作方式与上一教程相同,只有一个例外——我们将为我们感兴趣的每种严重性创建一个新的绑定。

val queueDeclared = channel.queueDeclare(
name = "",
durable = false,
exclusive = true,
autoDelete = true,
arguments = emptyMap()
)
val queueName = queueDeclared.queueName

for (severity in severities) {
channel.queueBind(queueName, "direct_logs", routingKey = severity)
}

总而言之

emitLogDirect 函数的代码

import dev.kourier.amqp.BuiltinExchangeType
import dev.kourier.amqp.Properties
import dev.kourier.amqp.connection.amqpConfig
import dev.kourier.amqp.connection.createAMQPConnection
import kotlinx.coroutines.CoroutineScope

suspend fun emitLogDirect(coroutineScope: CoroutineScope, severity: String, message: String) {
val config = amqpConfig {
server {
host = "localhost"
}
}
val connection = createAMQPConnection(coroutineScope, config)
val channel = connection.openChannel()

channel.exchangeDeclare(
"direct_logs",
BuiltinExchangeType.DIRECT,
durable = false,
autoDelete = false,
internal = false,
arguments = emptyMap()
)

channel.basicPublish(
message.toByteArray(),
exchange = "direct_logs",
routingKey = severity,
properties = Properties()
)
println(" [x] Sent '$severity':'$message'")

channel.close()
connection.close()
}

receiveLogsDirect 的代码

import dev.kourier.amqp.BuiltinExchangeType
import dev.kourier.amqp.connection.amqpConfig
import dev.kourier.amqp.connection.createAMQPConnection
import kotlinx.coroutines.CoroutineScope

suspend fun receiveLogsDirect(
coroutineScope: CoroutineScope,
severities: List<String>
) {
val config = amqpConfig {
server {
host = "localhost"
}
}
val connection = createAMQPConnection(coroutineScope, config)
val channel = connection.openChannel()

channel.exchangeDeclare(
"direct_logs",
BuiltinExchangeType.DIRECT,
durable = false,
autoDelete = false,
internal = false,
arguments = emptyMap()
)

val queueDeclared = channel.queueDeclare(
name = "",
durable = false,
exclusive = true,
autoDelete = true,
arguments = emptyMap()
)
val queueName = queueDeclared.queueName

if (severities.isEmpty()) {
System.err.println("Usage: receiveLogsDirect [info] [warning] [error]")
return
}

for (severity in severities) {
channel.queueBind(
queue = queueName,
exchange = "direct_logs",
routingKey = severity
)
}
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()
val routingKey = delivery.message.routingKey
println(" [x] Received '$routingKey':'$message'")
}

channel.close()
connection.close()
}

如果您只想将“警告”和“错误”(而不是“信息”)日志消息保存到文件,只需打开一个终端并输入:

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
receiveLogsDirect(this, listOf("warning", "error"))
}

如果您想在屏幕上看到所有日志消息,请打开一个新的终端并执行:

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
receiveLogsDirect(this, listOf("info", "warning", "error"))
}

例如,要发送一个 error 日志消息,只需键入:

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
emitLogDirect(this, "error", "Run. Run. Or it will explode.")
}

继续学习教程 5,了解如何根据模式监听消息。

© . This site is unofficial and not affiliated with VMware.