【问题标题】:is there a way to setup timeout in grpc server side?有没有办法在 grpc 服务器端设置超时?
【发布时间】:2019-10-14 17:51:50
【问题描述】:

无法使来自服务器端的 grpc 连接超时。客户端可能会建立连接但保持保持/睡眠状态,这会导致 grpc 服务器连接挂起。服务器端有没有办法在一定时间后断开连接或设置超时?

我们尝试从客户端断开连接,但无法从服务器端断开连接。在此链接Problem with gRPC setup. Getting an intermittent RPC unavailable error 中,Angad 表示可以但无法在 python 中定义这些参数。

我的代码sn-p:

def serve():
server = grpc.server(thread_pool=futures.ThreadPoolExecutor(max_workers=2), maximum_concurrent_rpcs=None, options=(('grpc.so_reuseport', 1),('grpc.GRPC_ARG_KEEPALIVE_TIME_MS', 1000)))
stt_pb2_grpc.add_ListenerServicer_to_server(Listener(), server)
server.add_insecure_port("localhost:50051")
print("Server starting in port "+str(50051))
server.start()
try:
    while True:
        time.sleep(60 * 60 * 24)
except KeyboardInterrupt:
    server.stop(0)
if __name__ == '__main__':
serve()

我希望在 python 中连接也应该从 grpc 服务器端超时。

【问题讨论】:

    标签: python-multithreading grpc-python


    【解决方案1】:

    简而言之,您可能会发现context.abort(...) 很有用,请参阅API reference。 gRPC Python 的底层 C-Core API 不支持服务器处理程序超时。所以,你必须在 Python 中实现自己的超时机制。

    您可以从其他 StackOverflow 问题中尝试一些解决方案。

    或者使用简单但开销很大的额外线程在一定时间后中止连接。它可能看起来像这样:

    _DEFAULT_TIME_LIMIT_S = 5
    
    class FooServer(FooServicer):
    
      def RPCWithTimeLimit(self, request, context):
        rpc_ended = threading.Condition()
        work_finished = threading.Event()
    
        def wrapper(...):
          YOUR_ACTUAL_WORK(...)
          work_finished.set()
          rpc_ended.notify_all()
    
        def timer():
          time.sleep(_DEFAULT_TIME_LIMIT_S)
          rpc_ended.notify_all()
    
        work_thread = threading.Thread(target=wrapper, ...)
        work_thread.daemon = True
        work_thread.start()
    
        timer_thread = threading.Thread(target=timer)
        timer_thread.daemon = True
        timer_thread.start()
    
        rpc_ended.wait()
        if work_finished.is_set():
          return NORMAL_RESPONSE
        else:
          context.abort(grpc.StatusCode.DEADLINE_EXCEEDED, 'RPC Time Out!')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-02
      • 2010-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 2013-01-14
      相关资源
      最近更新 更多