设置 RabbitMQ RPC 请求的超时时限
时间:2024-03-18
浏览:445
作者:佚名
在 RabbitMQ RPC 模型中,向主题发布消息时可以设置超时时限,以避免等待消费者对消息的响应时间过长。通过使用计时器或上下文,可以根据需要设定超时时间,当时间到期后,系统会自动取消请求,防止长时间等待。
问题内容
AMQP(RabbitMQ)RPC模型中向主题发布消息是否有超时?
我不想等待很长时间(超时后)消费者对生产者消息的答复。
参考:RPC(Go RabbitMQ 客户端)
解决方案
(示例代码使用 streadway/amqp)
您可以通过使用计时器来实现此目的,计时器的时间可以根据您的需要而定。然后使用 select 语句等待 rpc 响应和计时器通道:
func dorpc() ([]byte, error) {
// ...rpc setup code
timer := time.newtimer(2 * time.second)
for {
// waits until either a response from the rpc server
// is available or the timer expires
select {
case msg := <-msgs: // msgs is of type <-chan amqp.delivery
if msg.correlationid == correlationid {
return msg.body, nil
}
case <-timer.c:
return nil, errors.new("waiting for rpc response timed out or was cancelled")
}
}
}
要将超时控制权交给调用者,您可以使用上下文来代替计时器。它的工作方式相同,只不过现在您在上下文 done() 通道上选择:
func caller() {
// the caller can create a context with the desired timeout
ctx, cancel := context.WithTimeout(context.Background(), 2 * time.Second)
defer cancel()
doRPC(ctx)
}
func doRPC(ctx context.Context) ([]byte, error) {
// ...RPC setup code
for {
select {
case msg := <-msgs: // msgs is of type <-chan amqp.Delivery
if msg.CorrelationId == correlationID {
return msg.Body, nil
}
case <-ctx.Done():
return nil, errors.New("waiting for RPC response timed out or was cancelled")
}
}
}以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.30
11.30
11.30
11.30
11.30
11.30
11.30
11.30
热门专题
