我是 golang 的新手,我想重构我的代码,以便rabbitmq 初始化在另一个主要的函数中。所以我使用了一个结构指针(包含所有初始化的 rabbitmq 信息)并将其传递给发送函数,但它告诉我:无法发布消息:异常(504)原因:“通道/连接未打开”
结构:
type RbmqConfig struct {
q amqp.Queue
ch *amqp.Channel
conn *amqp.Connection
rbmqErr error
}
Run Code Online (Sandbox Code Playgroud)
初始化函数:
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
}
Run Code Online (Sandbox Code Playgroud)
主要的 :
config := initRabbitMq()
fmt.Println("queue name : ", config.q.Name)
sendMessage(config, <message_to_send>)
Run Code Online (Sandbox Code Playgroud)
在发送消息中:
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")
Run Code Online (Sandbox Code Playgroud)
如果有人有任何想法,那将非常有帮助。先感谢您
nev*_*ets 13
在 your 中init
,您编写了defer config.conn.Close()
,它将在函数返回时执行。也就是说,无论何时init
完成,您的连接都会关闭,从而导致未打开的连接。
您需要推迟连接在 main 中关闭,或者在您希望它关闭的地方延迟。
归档时间: |
|
查看次数: |
8367 次 |
最近记录: |