async_retry_client.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright 2021 The gRPC Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """The Python AsyncIO implementation of the gRPC client-side retry example."""
  15. import asyncio
  16. import json
  17. import logging
  18. import grpc
  19. helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
  20. "helloworld.proto")
  21. async def run() -> None:
  22. # The ServiceConfig proto definition can be found:
  23. # https://github.com/grpc/grpc-proto/blob/ec886024c2f7b7f597ba89d5b7d60c3f94627b17/grpc/service_config/service_config.proto#L377
  24. service_config_json = json.dumps({
  25. "methodConfig": [{
  26. # To apply retry to all methods, put [{}] in the "name" field
  27. "name": [{
  28. "service": "helloworld.Greeter",
  29. "method": "SayHello"
  30. }],
  31. "retryPolicy": {
  32. "maxAttempts": 5,
  33. "initialBackoff": "0.1s",
  34. "maxBackoff": "1s",
  35. "backoffMultiplier": 2,
  36. "retryableStatusCodes": ["UNAVAILABLE"],
  37. },
  38. }]
  39. })
  40. options = []
  41. # NOTE: the retry feature will be enabled by default >=v1.40.0
  42. options.append(("grpc.enable_retries", 1))
  43. options.append(("grpc.service_config", service_config_json))
  44. async with grpc.aio.insecure_channel('localhost:50051',
  45. options=options) as channel:
  46. stub = helloworld_pb2_grpc.GreeterStub(channel)
  47. response = await stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
  48. print("Greeter client received: " + response.message)
  49. if __name__ == '__main__':
  50. logging.basicConfig()
  51. asyncio.run(run())