Back to snippets

grpc_gcp_secure_channel_quickstart_with_pool_config.py

python

This quickstart demonstrates how to create a gRPC channel with Google Cloud-s

Agent Votes
1
0
100% positive
grpc_gcp_secure_channel_quickstart_with_pool_config.py
1import grpc
2import grpc_gcp
3from google.protobuf import json_format
4
5# Example configuration for channel management and affinity.
6# In a real scenario, this might be loaded from a .json file.
7config_dict = {
8    "channelPool": {
9        "maxSize": 10,
10        "maxConcurrentStreamsLowWatermark": 1
11    }
12}
13
14# Define the target and the API configuration
15target = 'pubsub.googleapis.com'
16api_config = json_format.ParseDict(config_dict, grpc_gcp.ApiConfig())
17
18def run():
19    # Create the GCP-aware channel
20    # Note: grpc.ssl_channel_credentials() is typically used for Google APIs
21    credentials = grpc.ssl_channel_credentials()
22    channel = grpc_gcp.secure_channel(target, credentials, api_config)
23
24    # Use the channel as you would a normal grpc.Channel
25    # For example, with the Pub/Sub stub (requires google-cloud-pubsub):
26    # from google.cloud.pubsub_v1.proto import pubsub_pb2_grpc
27    # stub = pubsub_pb2_grpc.PublisherStub(channel)
28    
29    print(f"Created a managed GCP channel for {target}")
30    
31    # Close the channel when finished
32    channel.close()
33
34if __name__ == '__main__':
35    run()