python - 你如何在 Python 的 gRPC 库中设置超时

标签 python grpc

我有一个 grpc 服务器/客户端,今天偶尔会挂起,从而导致问题。这是从 Flask 应用程序调用的,该应用程序正在检查后台工作进程以确保它处于事件状态/正常运行。要向 gRPC 服务器发出请求,我有:

try:
        health = self.grpc_client.Health(self.health_ping)
        if health.message == u'PONG':
            return {
                u'healthy': True,
                u'message': {
                    u'healthy': True,
                    u'message': u'success'
                },
                u'status_code': 200
            }
except Exception as e:
        if str(e.code()) == u'StatusCode.UNAVAILABLE':
            return {
                u'healthy': False,
                u'message': {
                    u'healthy': False,
                    u'message': (u'[503 Unavailable] connection to worker '
                                 u'failed')},
                u'status_code': 200}
        elif str(e.code()) == u'StatusCode.INTERNAL':
            return {
                u'healthy': False,
                u'message': {
                    u'healthy': False,
                    u'message': (u'[500 Internal] worker encountered '
                                 u'an error while responding')},
                u'status_code': 200}
        return {
            u'healthy': False,
            u'message': {u'healthy': False, u'message': e.message},
            u'status_code': 500
        }

客户端是一个 stub :

channel = grpc.insecure_channel(address)
stub = WorkerStub(channel)
return stub

原型(prototype)是:

syntax = "proto3";

option java_multiple_files = true;
option java_package = "com.company.project.worker";
option java_outer_classname = "ProjectWorker";
option objc_class_prefix = "PJW";

package projectworker;

service Worker {
  rpc Health (Ping) returns (Pong) {}
}

// The request message containing PONG
message Ping {
  string message = 1;
}

// The response message containing PONG
message Pong {
  string message = 1;
}

使用此代码,我将如何添加超时以确保我始终可以响应而不是失败和挂起?

最佳答案

timeout is an optional keyword parameter on RPC invocation所以你应该改变

health = self.grpc_client.Health(self.health_ping)

health = self.grpc_client.Health(self.health_ping, timeout=my_timeout_in_seconds)

.

关于python - 你如何在 Python 的 gRPC 库中设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43869397/

相关文章:

gRPC:RPC 调用的随机 CANCELED 异常

python - Python-如何规范视频文件中的音频?

Python:如何比较多个作为参数的字符串的长度?

python - 使用 QT 设计器创建的 PyQt5 程序从终端打开时不显示任何窗口

python - Django 中所有 Celery worker/内存缓存的全局可访问对象

python - 在 grpc python 中处理异步流请求

android - 为什么 Xamarin Android 无法发送 GRPC/Http2 请求?

grpc - 为什么 grpc-web 需要特使代理?

c# - 从 python 调用 C# 库

grpc - gRPC python 的级联超时传播