簡體   English   中英

如何在Python的gRPC庫中設置超時

[英]How do you set a timeout in Python's gRPC Library

我有一個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
        }

客戶端是一個存根:

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

原型是:

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是RPC調用的可選關鍵字參數,因此您應該更改

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

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

您可能還希望以不同於其他錯誤的方式捕獲和處理超時。 可悲的是,這個主題的文檔並不是很好,所以這就是你所擁有的:

try:
    health = self.grpc_client.Health(self.health_ping, timeout=my_timeout_in_seconds)
except grpc.RpcError as e:
    e.details()
    status_code = e.code()
    status_code.name
    status_code.value

超時將返回DEADLINE_EXCEEDED status_code.value。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM