If a gRPC client starts before the server, it exits with an exception. The application I am working on starts a bunch of servers and clients (near) simultaneously, however, and I have to be robust with respect to execution order. If the client starts before the server, I want it to wait until the server shows up.
I modified the HelloWorld python client example as follows:
done = False
while not done:
try:
response = stub.SayHello(helloworld_pb2.HelloRequest(name='you'), timeout=1)
print("Greeter client received: " + response.message)
done = True
except:
print('Waiting for server connect...')
time.sleep(1)
Run Code Online (Sandbox Code Playgroud)
so now if I start the client before the server, I get the 'Waiting for server connect...' message scrolling up my terminal window as expected. Then I start the server, and it connects... eventually. In fact it takes about ten seconds before the 'Hello you' messages appears, which is surprisingly long. Why might it be so slow, and is there a robust way to check for server connection?
import grpc
TIMEOUT_SEC = 15
def grpc_server_on(channel) -> bool:
try:
grpc.channel_ready_future(channel).result(timeout=TIMEOUT_SEC)
return True
except grpc.FutureTimeoutError:
return False
Run Code Online (Sandbox Code Playgroud)
该channel_ready_future函数允许客户端等待指定的超时持续时间(以秒为单位),以便服务器准备就绪。如果我们的客户端超时,它就会上升。
看看ChannelConnectivity-我是一名Go程序员,但在python中应该是相同的。我要做的是创建while while / for循环,并且当“ ChannelConnectivity”设置为“ READY”时,我从连接中创建客户端,然后继续。
| 归档时间: |
|
| 查看次数: |
3461 次 |
| 最近记录: |