Golang - RabbitMq:channel/connection 未打开

Golang - RabbitMq : channel/connection is not open

我是 golang 的新手,我想重构我的代码,以便 rabbitmq 初始化在 main.c 的另一个函数中。所以我使用一个结构指针(包含所有已初始化的 rabbitmq 信息)并将其传递给发送函数,但它告诉我:无法发布消息:异常(504)原因:"channel/connection is not open"

结构:

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")

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

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

您需要在 main 或您希望它关闭的地方延迟关闭连接。