Debian Codegraph @

examples/python/retry/async_retry_client.py

raw
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
16 import asyncio
17 import json
18 import logging
19
20 import grpc
21
22 helloworld_pb2, helloworld_pb2_grpc = grpc.protos_and_services(
23 "helloworld.proto")
24
25
26 async def run() -> None:
27 # The ServiceConfig proto definition can be found:
28 # https://github.com/grpc/grpc-proto/blob/ec886024c2f7b7f597ba89d5b7d60c3f94627b17/grpc/service_config/service_config.proto#L377
29 service_config_json = json.dumps({
30 "methodConfig": [{
31 # To apply retry to all methods, put [{}] in the "name" field
32 "name": [{
33 "service": "helloworld.Greeter",
34 "method": "SayHello"
35 }],
36 "retryPolicy": {
37 "maxAttempts": 5,
38 "initialBackoff": "0.1s",
39 "maxBackoff": "1s",
40 "backoffMultiplier": 2,
41 "retryableStatusCodes": ["UNAVAILABLE"],
42 },
43 }]
44 })
45 options = []
46 # NOTE: the retry feature will be enabled by default >=v1.40.0
47 options.append(("grpc.enable_retries", 1))
48 options.append(("grpc.service_config", service_config_json))
49 async with grpc.aio.insecure_channel('localhost:50051',
50 options=options) as channel:
51 stub = helloworld_pb2_grpc.GreeterStub(channel)
52 response = await stub.SayHello(helloworld_pb2.HelloRequest(name='you'))
53 print("Greeter client received: " + response.message)
54
55
56 if __name__ == '__main__':
57 logging.basicConfig()
58 asyncio.run(run())