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


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.rbmqErr = config.conn.Channel()
    failOnError(config.rbmqErr, "Failed to open a channel")

    config.q, config.rbmqErr =
        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 =
        "",           // exchange
        config.q.Name,       // routing key
        false,        // mandatory
            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.

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



  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况