【问题标题】:Golang - RabbitMq : channel/connection is not openGolang - RabbitMq:通道/连接未打开
【发布时间】:2016-04-13 11:09:30
【问题描述】:

我是 golang 的新手,我想重构我的代码,以便 rabbitmq 初始化在另一个 main 函数中。所以我使用了一个结构指针(包含所有初始化的rabbitmq信息)并将其传递给发送函数,但它告诉我:无法发布消息:异常(504)原因:“通道/连接未打开”

结构:

type RbmqConfig struct {
    q amqp.Queue
    ch *amqp.Channel
    conn *amqp.Connection
    rbmqErr error
}

初始化函数:

func initRabbitMq() *RbmqConfig {

    config := &RbmqConfig{}

    config.conn, config.rbmqErr = amqp.Dial("amqp://guest:guest@localhost:5672/")
    failOnError(config.rbmqErr, "Failed to connect to RabbitMQ")
    defer config.conn.Close()

    config.ch, config.rbmqErr = config.conn.Channel()
    failOnError(config.rbmqErr, "Failed to open a channel")
    defer config.ch.Close()

    config.q, config.rbmqErr = config.ch.QueueDeclare(
        "<my_queue_name>",
        true,   // durable
        false,   // delete when unused
        false,   // exclusive
        false,   // no-wait
        nil,     // arguments
    )
    failOnError(config.rbmqErr, "Failed to declare a queue")

    return config
}

主要:

config := initRabbitMq()

fmt.Println("queue name : ", config.q.Name)

sendMessage(config, <message_to_send>)

在发送消息中:

func sendMessage(config *RbmqConfig, <message_to_send>) {

    config.rbmqErr = config.ch.Publish(
        "",           // exchange
        config.q.Name,       // routing key
        false,        // mandatory
        false,
        amqp.Publishing{
            DeliveryMode: amqp.Persistent,
            ContentType:  "text/plain",
            Body:         []byte(<message_to_send>),
        })
    failOnError(config.rbmqErr, "Failed to publish a message")

如果有人有任何想法,那将非常有帮助。提前谢谢你

【问题讨论】:

    标签: go rabbitmq


    【解决方案1】:

    在您的init 中,您编写了defer config.conn.Close(),它将在函数返回时执行。也就是说,每当init完成时,你的连接就会被关闭,从而导致连接未打开。

    您需要推迟在 main 中关闭连接,或者在您希望它关闭的地方。

    【讨论】:

    • 我知道关闭连接的好习惯,但出于好奇,如果我不关闭它会发生什么
    • 我也遇到了同样的问题,基本上exchange的名字不应该是queue的名字
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 2019-02-23
    • 2016-05-06
    相关资源
    最近更新 更多