Python grpc超时机制代码示例
工作中遇到一个问题,上游服务通过grpc调用下游服务,但是由于下游服务负载太高导致上游服务的调用会随机出现超时的情况,但是有一点不太明确:超时之后,下游服务还会继续进行计算么?
于是自己写了一个damon试了一下:
client:
#Copyright2015gRPCauthors.
#
#LicensedundertheApacheLicense,Version2.0(the"License");
#youmaynotusethisfileexceptincompliancewiththeLicense.
#YoumayobtainacopyoftheLicenseat
#
#http://www.apache.org/licenses/LICENSE-2.0
#
#Unlessrequiredbyapplicablelaworagreedtoinwriting,software
#distributedundertheLicenseisdistributedonan"ASIS"BASIS,
#WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
#SeetheLicenseforthespecificlanguagegoverningpermissionsand
#limitationsundertheLicense.
"""ThePythonimplementationoftheGRPChelloworld.Greeterclient."""
from__future__importprint_function
importlogging
importgrpc
importhelloworld_pb2
importhelloworld_pb2_grpc
defrun():
#NOTE(gRPCPythonTeam):.close()ispossibleonachannelandshouldbe
#usedincircumstancesinwhichthewithstatementdoesnotfittheneeds
#ofthecode.
withgrpc.insecure_channel('localhost:50051')aschannel:
stub=helloworld_pb2_grpc.GreeterStub(channel)
response=stub.SayHello(helloworld_pb2.HelloRequest(name='you'),timeout=30)
print("Greeterclientreceived:"+response.message)
if__name__=='__main__':
logging.basicConfig()
run()
server:
#Copyright2015gRPCauthors.
#
#LicensedundertheApacheLicense,Version2.0(the"License");
#youmaynotusethisfileexceptincompliancewiththeLicense.
#YoumayobtainacopyoftheLicenseat
#
#http://www.apache.org/licenses/LICENSE-2.0
#
#Unlessrequiredbyapplicablelaworagreedtoinwriting,software
#distributedundertheLicenseisdistributedonan"ASIS"BASIS,
#WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
#SeetheLicenseforthespecificlanguagegoverningpermissionsand
#limitationsundertheLicense.
"""ThePythonimplementationoftheGRPChelloworld.Greeterserver."""
fromconcurrentimportfutures
importtime
importlogging
importgrpc
importhelloworld_pb2
importhelloworld_pb2_grpc
_ONE_DAY_IN_SECONDS=60*60*24
classGreeter(helloworld_pb2_grpc.GreeterServicer):
defSayHello(self,request,context):
count=0
whilecount<10:
print('time:%s'%(time.time()))
time.sleep(5)
returnhelloworld_pb2.HelloReply(message='Hello,%s!'%request.name)
defserve():
server=grpc.server(futures.ThreadPoolExecutor(max_workers=10))
helloworld_pb2_grpc.add_GreeterServicer_to_server(Greeter(),server)
server.add_insecure_port('[::]:50051')
server.start()
try:
whileTrue:
time.sleep(_ONE_DAY_IN_SECONDS)
exceptKeyboardInterrupt:
server.stop(0)
if__name__=='__main__':
logging.basicConfig()
serve()
这两个例子就是在grpc官方提供的python例子上做了一下小的改动,得到的结果是:当client超时报错退出之后,server还是会继续进行计算,直到结束,那如果是这样的话,超时的机制对于server来说是没有作用的,即使client已经不再等待这个结果了,但是server还是会继续计算,浪费server的资源。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。