简体   繁体   English

python grpc 客户端如何管理连接?

[英]how python grpc client manage connections?

When exactly a grpc client create and close connections? grpc 客户端何时创建和关闭连接?
I begin the code with:我开始代码:

channel = grpc.insecure_channel('localhost:8888')
stub = myservice_pb2_grpc.MyServiceStub(channel)

Does declaring a channel creates a single socket for the entire lifetime of the process?声明一个channel是否会在进程的整个生命周期中创建一个套接字?
Cause even if I give invalid address to insecure_channel() I don't see any error until I make the first request.因为即使我给insecure_channel()提供了无效的地址,在我提出第一个请求之前我也看不到任何错误。

Or, the socket is created only when request is made and closed afterwards?或者,仅在发出请求并随后关闭套接字时才创建套接字?

In gRPC Python a channel object corresponds to one or more TCP connections, depending on your load balancing policy.在 gRPC Python 中,通道 object 对应于一个或多个 TCP 连接,具体取决于您的负载平衡策略。 If no load balancing policy is selected (which seems to be the vast majority of usage), then yes, a channel corresponds to a single TCP connection.如果没有选择负载均衡策略(这似乎是绝大多数使用情况),那么是的,一个通道对应一个 TCP 连接。

The connections represented by a channel will remain alive as long as the channel object itself is open.只要通道 object 本身是打开的,由通道表示的连接将保持活动状态。 It is therefore recommended that you reuse channels across many RPC invocations with a client process.因此,建议您在客户端进程的许多 RPC 调用中重用通道。 It is also recommended that you close a channel once it is no longer needed.建议您在不再需要某个频道时将其关闭。

There are two ways to accomplish this.有两种方法可以做到这一点。 The first is to manually call the close method:第一种是手动调用close方法:

channel = grpc.insecure_channel('localhost:8888')
# send some RPCs
channel.close()

The other is to use the context manager:另一种是使用上下文管理器:

with grpc.insecure_channel('localhost:8888') as channel:
  # send some RPCs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM