英文:
Why will RabbitMQ's PublishWithContext not work with Go?
问题
我正在通过使用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) {
// 初始化与RabbitMQ的连接
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
// 初始化通道
ch, err := conn.Channel()
// 初始化队列
q, err := ch.QueueDeclare(
"hello", // 名称
false, // 持久化
false, // 不在使用时删除
false, // 独占
false, // 不等待
nil, // 参数
)
// 设置上下文
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
body := "Hello World!"
err = ch.PublishWithContext( // 这里可能会出错
ctx, // 上下文
"", // 交换机
q.Name, // 路由键
false, // 强制性
false, // 立即发送
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
})
return &RabbitMQ{}, nil
}
据我所知,根据文档,这应该是正确的实现方式,所以我不确定为什么会出错。
我尝试通过谷歌搜索来解决这个问题,但没有找到帮助。我正在使用Go 1.19,也许是版本的问题?
英文:
I am learning RabbitMQ through building a small application in GoLang - following this example here: https://www.rabbitmq.com/tutorials/tutorial-one-go.html. My project has the following structure:
project
└───cmd
│ └───api
│ │ main.go
│ └───internal
│ │ rabbitmq.go
And in cmd/internal/rabbitmq.go
I have the following code - (errs are delt with):
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
}
As far as I can tell, from the documentation, this is how it should be implemented, so I'm not sure why it is erroring.
I've tried googling to find help with this issue but to no avail. I am using Go 1.19, maybe it is an issue with that?
答案1
得分: 0
感谢 @oakad,这是一个简单的修复!问题是我使用的RabbitMQ版本较旧,所以我只需要将我的 go.mod
文件更改为:
require github.com/rabbitmq/amqp091-go v1.4.0
英文:
Thanks to @oakad, this was a simple fix! The issue was the version of RabbitMQ I was using was an older one so I just need to change my go.mod
from:
require github.com/rabbitmq/amqp091-go v1.1.0
To:
require github.com/rabbitmq/amqp091-go v1.4.0
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论