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

标签 go rabbitmq rpc amqp

向 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/

相关文章:

docker - 使用 docker-compose 安装包

go - 为什么32字节哈希的长度是二进制的267位而不是256位?

windows - 如何使用 docker 容器在浏览器中打开 rabbitmq?

spring-boot - 将 Spring Cloud Sleuth 与 Spring boot amqp 集成

python - RabbitMQ Python Pika - 多个消息的连接处理

c++ - 转储apache Thrift 消息以进行调试?

go - 错误 : EOF for reading XML body of Post request

go - Uber Zap 记录器不在日志语句中打印调用者信息

java - 在 grpc 拦截器中使用 ThreadLocal 的正确方法是什么?

javascript - Python函数rpc方法调用晚于js文件中的do_action() Odoo 11