Using keepalive based channel connectivity checks and TCP_USER_TIMEOUT to avoid blocking: | |
----------------------------------------------------------------------------------------- | |
import grpc | |
import time | |
import helloworld_pb2 | |
import helloworld_pb2_grpc | |
def run(): | |
channel_opts = [ | |
( | |
# Interval at which grpc will send keepalive pings | |
'grpc.keepalive_time_ms', | |
1000 | |
), | |
( | |
# Amount of time grpc waits for a keepalive ping to be | |
# acknowledged before deeming the connection unhealthy and closing | |
# this also sets TCP_USER_TIMEOUT for the underlying socket to this value | |
'grpc.keepalive_timeout_ms', | |
500 | |
) | |
] | |
channel = grpc.insecure_channel("localhost:1234", options=channel_opts) | |
stub = helloworld_pb2_grpc.GreeterStub(channel) | |
while True: | |
# Some large message | |
msg = 'Hello' * 100000 | |
# Check that the connectivity state of the channel is connected (2) | |
# Passing True here tells the channel attempt to connect if disconnected | |
# https://github.com/grpc/grpc/blob/2cec9c5344014db548448bd7fbbe04e7c33635be/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi#L469 | |
if channel._channel.check_connectivity_state(True) == 2: | |
try: | |
# Make RPC call supplying a sane timeout value | |
response = stub.SayHello(helloworld_pb2.HelloRequest(name=msg), timeout=0.3) | |
except RpcError as e: | |
# Handle timeouts here | |
pass | |
else: | |
# Do something with response | |
time.sleep(0.01) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment