在 Go amqp 客户端中设置连接友好名称

Set connection friendly name in Go amqp client

我在我的应用程序中使用 http://github.com/streadway/amqp 包来处理与远程 RabbitMQ 服务器的连接。一切正常,工作正常,但我有一个问题。

连接的当前名称是“ip:port”,因此当有多个连接来自同一个IP+端口时,它们变得难以区分。如果你能为每个连接指定一个名字就太好了。

有没有办法为每个连接设置一个独特的友好名称?

RabbitMQ 3.6.5 添加了连接客户端报告友好名称 字符串值的功能,以识别用于管理目的的连接。这严格来说是一个标识符,因为它是客户端报告的,所以除了连接的弱识别之外,不能依赖它。 release notes 状态:

Clients now can provide a human-readable connection name that will be displayed in the management UI... In order to use this feature, set the connection_name key in client properties. Note that this name doesn’t have to be unique and cannot be used as a connection identifier, for example, in HTTP API requests.


解决方案

如果您使用的是足够新的 RabbitMQ 版本,您可以在使用 streadway/amqp 建立连接时设置此参数,方法是在建立初始连接时传递 amqp.Config 的实例。 Properties 字段允许指定连接的自定义属性。

下面的示例程序使用环境变量 AMQP_URL 中提供的 AMQP URL 打开连接,使用作为第一个命令行参数传递给调用的连接名称进行标识。

package main

import (
    "log"
    "os"

    "github.com/streadway/amqp"
)

func main() {
    amqpUrl := os.Getenv("AMQP_URL")

    cfg := amqp.Config{
        Properties: amqp.Table{
            "connection_name": os.Args[1],
        },
    }

    conn, err := amqp.DialConfig(amqpUrl, cfg)
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()

    <-(chan struct{})(nil)
}

使用以下命令行启动多个实例以连接到本地 RabbitMQ 实例:

AMQP_URL=amqp://admin:password@localhost:5672 go run ./main.go connX

用数字代替 X 在 RabbitMQ 管理网站 "Connections" 页面中产生以下输出 UI:

并且各个连接详细信息页面显示 "Client-provided name" 详细值下的值: