【问题标题】:How to interrupt a grpc call gracefully in the client side?如何在客户端优雅地中断 grpc 调用?
【发布时间】:2022-11-17 03:47:14
【问题描述】:

我写了一个客户端,它启动到 grpc 服务器的多个连接来请求一些东西。一旦收到回复,我想停止所有其他 grpc 调用。我使用一个事件来控制这个过程。

但是,我不知道如何优雅地终止 grpc 调用。以下是我所做的。该代码将导致错误:打开的文件过多。有人可以帮我吗?如何优雅地终止 grpc 调用?

def request_something(event):
    with grpc.insecure_channel(ip) as channel:
        stub = GrpcServiceStub(channel)
        req = Request()
        response_future = stub.GetResponse.future(req)

        while not response_future.done() and not event.is_set():
            time.sleep(0.1)

        if event.is_set():
            # try to interrupt grpc call
            if not response_future.cancel():
                while not response_future.done():
                    time.sleep(0.1)
            print("Stop request")
            channel.close()
            return

        response = response_future.result()
    return response


event = Event()
with futures.ThreadPoolExecutor(max_workers=...) as executor:
     res = []
     for _ in range(...):
         future = executor.submit(request_something, event)
         res.append(future)
         for future in futures.as_completed(res):
             print("now we get the first response")
             event.set()
             executor.shutdown(wait=False)

【问题讨论】:

    标签: python multithreading grpc-python


    【解决方案1】:

    您可以在客户端调用 (https://grpc.github.io/grpc/python/grpc.html#grpc.UnaryUnaryMultiCallable.future) 上使用 future API,然后在 futures (https://grpc.github.io/grpc/python/grpc.html#grpc.Future.cancel) 上调用 cancel。

    Python 中的完整取消示例:https://github.com/grpc/grpc/tree/master/examples/python/cancellation

    希望这可以帮助!

    【讨论】:

      猜你喜欢
      • 2021-05-03
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 2020-07-22
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 2019-03-28
      相关资源
      最近更新 更多