登录
首页 >  Golang >  Go问答

设置 RabbitMQ RPC 请求的超时时限

来源:stackoverflow

时间:2024-03-18 17:15:31 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学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>