我是 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")
如果有人有任何想法,那将非常有帮助。先感谢您
蝴蝶刀刀
相关分类