为何不支持在 Go 中使用 RabbitMQ 的 PublishWithContext?
时间:2024-03-03
浏览:205
作者:佚名
你在学习Golang相关的知识吗?本文《为何不支持在 Go 中使用 RabbitMQ 的 PublishWithContext?》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!
问题内容
我正在通过在 golang 中构建一个小型应用程序来学习 rabbitmq - 按照此处的示例:https://www.rabbitmq.com/tutorials/tutorial-one-go.html。我的项目具有以下结构:
project └───cmd │ └───api │ │ main.go │ └───internal │ │ rabbitmq.go
在 cmd/internal/rabbitmq.go 中,我有以下代码 - (错误被删除):
import (
...
amqp "github.com/rabbitmq/amqp091-go"
)
func NewRabbitMQ() (*RabbitMQ, error) {
// Initialise connection to RabbitMQ
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
// Initialise Channel
ch, err := conn.Channel()
// Initialise Queue
q, err := ch.QueueDeclare(
"hello", // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
// Set Context
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
body := "Hello World!"
err = ch.PublishWithContext( // errors here
ctx, // context
"", // exchange
q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
})
return &RabbitMQ{}, nil
}
据我所知,从文档中可以看出,这就是它应该如何实现的,所以我不确定为什么会出错。
我尝试通过谷歌搜索来寻找有关此问题的帮助,但没有成功。我使用的是 go 1.19,也许这是一个问题?
正确答案
感谢@oakad,这是一个简单的修复!问题是我使用的 rabbitmq 版本较旧,因此我只需要将 go.mod 更改为:
require github.com/rabbitmq/amqp091-go v1.1.0
致:
require github.com/rabbitmq/amqp091-go v1.4.0
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
