简体   繁体   中英

how python grpc client manage connections?

When exactly a grpc client create and close connections?
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?
Cause even if I give invalid address to insecure_channel() I don't see any error until I make the first request.

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. 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.

The connections represented by a channel will remain alive as long as the channel object itself is open. It is therefore recommended that you reuse channels across many RPC invocations with a client process. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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