gpt4 book ai didi

go - 如何为 RabbitMQ RPC 请求设置超时?

转载 作者:行者123 更新时间:2023-12-01 21:13:57 37 4
gpt4 key购买 nike

向 AMQP (RabbitMQ) RPC 模型中的主题发布消息是否有任何超时?

我不想等待很长时间(超时后)消费者对生产者消息的回答。

引用:RPC (Go RabbitMQ Client)

最佳答案

(示例代码使用 streadway/amqp )
您可以使用 来实现此目的。计时器 ,它可以像你希望的那样短。然后使用 select 等待 RPC 响应和计时器 channel 。陈述:

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() channel :

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")
}
}
}

关于go - 如何为 RabbitMQ RPC 请求设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61197332/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com