dongyuan1902 2016-04-12 17:05 采纳率: 0%
浏览 1530
已采纳

Golang-RabbitMq:通道/连接未打开

I'm new to golang, and I would like to refactorate my code so that the rabbitmq initialization is in another function that main. So I use a struct pointer (containing all the rabbitmq infos initilized) and pass it to the send function, but it tells me : Failed to publish a message: Exception (504) Reason: "channel/connection is not open"

struct :

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

the init function :

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
}

main :

config := initRabbitMq()

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

sendMessage(config, <message_to_send>)

in send message :

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

If someone has any idea, that would be very helpful. Thank you in advance

  • 写回答

1条回答 默认 最新

  • dongxun4110 2016-04-13 03:09
    关注

    Inside your init, you wrote defer config.conn.Close(), which will be executed when the function return. That is to say, whenever init finished, your connection will be closed, which causes unopen connection.

    You need to defer the connection closing in main, or somewhere you want it to be closed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵