Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Cette page, qui présente des détails propres à Cloud Run, s'adresse aux développeurs qui souhaitent utiliser gRPC afin de connecter un service Cloud Run à d'autres services, par exemple pour fournir une communication simple et hautes performances entre des microservices internes. Avec Cloud Run, vous pouvez utiliser tous les types gRPC en streaming ou unaire.
Exemples d'utilisation possible :
Communication entre des microservices internes.
Charges de données élevées (gRPC utilise des tampons de protocole, qui sont jusqu'à sept fois plus rapides que les appels REST).
Seule une définition de service simple est nécessaire, vous ne souhaitez pas écrire une bibliothèque cliente complète.
Utilisez des gRPC en streaming sur votre serveur gRPC pour créer des applications et des API plus réactives.
Pour intégrer votre service à gRPC, procédez comme suit :
Configurez votre service pour qu'il utilise HTTP/2 si vous utilisez gRPC en streaming. HTTP/2 est la méthode de transport pour le streaming gRPC.
Définissez les messages de requête et les réponses dans un fichier proto, puis compilez-les.
Créez un serveur gRPC pour gérer les requêtes et renvoyer des réponses : il doit écouter la variable d'environnement PORT.
Créez un client qui envoie des requêtes et gère les réponses du serveur gRPC.
Vous pouvez éventuellement ajouter une authentification.
Créez et déployez votre service.
Configurer votre service pour utiliser HTTP/2
Google recommande de configurer votre service pour en HTTP/2 si vous utilisez gRPC avec Cloud Run. Bien que certaines fonctionnalités gRPC de base fonctionnent sans HTTP/2, de nombreuses fonctionnalités gRPC, telles que le streaming et les métadonnées, nécessitent HTTP/2.
Définir et compiler des messages dans un fichier proto
Vous n'avez pas besoin d'ajouter d'éléments supplémentaires ou propres à Cloud Run dans vos définitions de proto. Comme pour toute autre utilisation de gRPC, vous utilisez des tampons de protocole gRPC pour les définitions de service et la sérialisation des données.
Créer un client gRPC
Vous n'avez pas besoin d'ajouter d'éléments supplémentaires ou propres à Cloud Run à un client qui utilise gRPC : suivez les documents gRPC sur l'utilisation des définitions de service dans le code client et les exemples de clients fournis dans les tutoriels gRPC propres aux différents langages.
Autoscaling et équilibrage de charge
Cloud Run utilise des équilibreurs de charge gérés par Google qui maintiennent des connexions distinctes entre les clients et vos instances Cloud Run.
Avec gRPC, l'autoscaling se comporte comme suit :
Les connexions gRPC des clients se terminent au niveau de l'équilibreur de charge périphérique. L'ajustement des paramètres KeepAlive n'affecte que la connexion à l'équilibreur de charge, et pas les instances Cloud Run. Le client ne reconnaît pas le moment où une instance est arrêtée.
Lors du scaling vertical, l'équilibreur de charge ferme les connexions en envoyant des messages GOAWAY aux instances de backend lorsqu'elles s'arrêtent.
Pendant le scaling horizontal, l'équilibreur de charge crée des connexions aux instances de backend.
Toutes ces opérations sont transparentes pour les clients.
Lors de l'autoscaling, de nombreuses instances peuvent démarrer et être multiplexées en une seule connexion entre le client et l'équilibreur de charge proxy.
La simultanéité est déterminée par le nombre maximal de requêtes simultanées par instance pour les messages. En cas de diffusion en flux continu, chaque flux est comptabilisé une fois dans le nombre maximal de requêtes simultanées.
Écouter des requêtes gRPC dans un service Cloud Run
La seule condition requise pour un serveur gRPC exécuté dans Cloud Run est d'écouter le port spécifié par la variable d'environnement PORT, comme indiqué dans le code suivant :
Go
funcmain(){log.Printf("grpc-ping: starting server...")port:=os.Getenv("PORT")ifport==""{port="8080"log.Printf("Defaulting to port %s",port)}listener,err:=net.Listen("tcp",":"+port)iferr!=nil{log.Fatalf("net.Listen: %v",err)}grpcServer:=grpc.NewServer()pb.RegisterPingServiceServer(grpcServer,&pingService{})iferr=grpcServer.Serve(listener);err!=nil{log.Fatal(err)}}
Ouvrir une connexion gRPC à un service
Pour ouvrir une connexion gRPC à un service afin d'envoyer des messages gRPC, vous devez spécifier le domaine hôte, qui est l'URL du service Cloud Run ou le domaine personnalisé mappé avec ce service, ainsi que le port 443, qui est le port censé être utilisé par gRPC.
Go
import("crypto/tls""crypto/x509""google.golang.org/grpc""google.golang.org/grpc/credentials")// NewConn creates a new gRPC connection.// host should be of the form domain:port, e.g., example.com:443funcNewConn(hoststring,insecurebool)(*grpc.ClientConn,error){varopts[]grpc.DialOptionifhost!=""{opts=append(opts,grpc.WithAuthority(host))}ifinsecure{opts=append(opts,grpc.WithInsecure())}else{// Note: On the Windows platform, use of x509.SystemCertPool() requires// Go version 1.18 or higher.systemRoots,err:=x509.SystemCertPool()iferr!=nil{returnnil,err}cred:=credentials.NewTLS(&tls.Config{RootCAs:systemRoots,})opts=append(opts,grpc.WithTransportCredentials(cred))}returngrpc.Dial(host,opts...)}
Envoyer des requêtes gRPC sans authentification
L'exemple suivant montre comment envoyer une requête sans authentification, à l'aide d'une connexion gRPC configurée comme indiqué précédemment.
Go
import("context""time"pb"github.com/GoogleCloudPlatform/golang-samples/run/grpc-ping/pkg/api/v1""google.golang.org/grpc")// pingRequest sends a new gRPC ping request to the server configured in the connection.funcpingRequest(conn*grpc.ClientConn,p*pb.Request)(*pb.Response,error){ctx,cancel:=context.WithTimeout(context.Background(),30*time.Second)defercancel()client:=pb.NewPingServiceClient(conn)returnclient.Send(ctx,p)}
Envoyer des requêtes gRPC avec authentification
L'exemple suivant montre comment utiliser l'authentification entre les services, si le service appelant dispose d'une autorisation d'appel sur le service destinataire. Notez que ce code crée un en-tête d'autorisation doté du jeton d'identité approprié : cela est obligatoire. Les autorisations requises et l'en-tête d'autorisation sont décrites en détail sur la page Authentification de service à service.
Go
import("context""fmt""time""google.golang.org/api/idtoken""google.golang.org/grpc"grpcMetadata"google.golang.org/grpc/metadata"pb"github.com/GoogleCloudPlatform/golang-samples/run/grpc-ping/pkg/api/v1")// pingRequestWithAuth mints a new Identity Token for each request.// This token has a 1 hour expiry and should be reused.// audience must be the auto-assigned URL of a Cloud Run service or HTTP Cloud Function without port number.funcpingRequestWithAuth(conn*grpc.ClientConn,p*pb.Request,audiencestring)(*pb.Response,error){ctx,cancel:=context.WithTimeout(context.Background(),30*time.Second)defercancel()// Create an identity token.// With a global TokenSource tokens would be reused and auto-refreshed at need.// A given TokenSource is specific to the audience.tokenSource,err:=idtoken.NewTokenSource(ctx,audience)iferr!=nil{returnnil,fmt.Errorf("idtoken.NewTokenSource: %w",err)}token,err:=tokenSource.Token()iferr!=nil{returnnil,fmt.Errorf("TokenSource.Token: %w",err)}// Add token to gRPC Request.ctx=grpcMetadata.AppendToOutgoingContext(ctx,"authorization","Bearer "+token.AccessToken)// Send the request.client:=pb.NewPingServiceClient(conn)returnclient.Send(ctx,p)}
Exemple de code pour le streaming gRPC
Pour obtenir un exemple de code, reportez-vous à l'implémentation de RouteGuide dans le tutoriel gRPC "Principes de base" dans la langue de votre choix. Lorsque vous utilisez Go, par exemple, reportez-vous à la section Mettre en œuvre RouteGuide.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[],[],null,["# Using gRPC\n\nThis page shows Cloud Run-specific details for developers who\nwant to use [gRPC](https://grpc.io/) to connect a\nCloud Run service with other services, for example, to provide\nsimple, high performance communication between internal\nmicroservices. You can use [all gRPC types](https://grpc.io/docs/what-is-grpc/core-concepts#rpc-life-cycle),\nstreaming or unary, with Cloud Run.\n\nPossible use cases include:\n\n- Communication between internal microservices.\n- High loads of data (gRPC uses [protocol buffers](https://developers.google.com/protocol-buffers), which are up to seven times faster than REST calls).\n- Only a simple service definition is needed, you don't want to write a full client library.\n- Use streaming gRPCs in your gRPC server to build more responsive applications and APIs.\n\nTo integrate your service with gRPC:\n\n- Configure your service to use HTTP/2 if you are using streaming gRPC. HTTP/2 is the transport method for gRPC streaming.\n- Define the request messages and responses in a proto file and compile them.\n- Create a gRPC server to handle requests and return responses: it should listen to the `PORT` environment variable.\n- Create a client that sends requests and handles responses from the gRPC server.\n- Optionally, add authentication.\n- Build and deploy your service.\n\nConfiguring your service to use HTTP/2\n--------------------------------------\n\nGoogle recommends [configuring your service to use HTTP/2](/run/docs/configuring/http2) if you\nuse gRPC with Cloud Run. Although some simple gRPC features work\nwithout using HTTP/2, many gRPC features, such as streaming and metadata, require HTTP/2.\n\nDefining and compiling messages in a proto file\n-----------------------------------------------\n\nThere are no extra or Cloud Run-specific things to add to your proto\ndefinitions. Just as with any other use of gRPC, you use\n[gRPC protocol buffers](https://grpc.io/docs/guides/#working-with-protocol-buffers)\nfor service definitions and data serialization.\n\nCreating a gRPC client\n----------------------\n\nThere are no extra or Cloud Run specific things to add to a client\nthat uses gRPC: follow the gRPC docs on using service definitions in\n[client code](https://grpc.io/docs/guides/concepts/#using-the-api), and the\nsample clients provided in the language-specific\n[gRPC tutorials](https://grpc.io/docs/languages).\n\nAutoscaling and load balancing\n------------------------------\n\nCloud Run uses Google-managed load balancers that keep separate\nconnections between clients and your Cloud Run instances.\nWith gRPC, autoscaling behaves as follows:\n\n- gRPC connections from clients end at the edge load balancer. Adjusting `KeepAlive` settings only affects the connection to the load balancer, not the Cloud Run instances. The client doesn't recognize when an instance drops.\n- During scale-in, the load balancer closes connections by sending GOAWAY messages to the backend instances as they shut down.\n- During scale-out, the load balancer creates new connections to the backend instances. All these operations are transparent to clients.\n- During autoscaling, many instances can start up and multiplex into a single connection between the client and the proxy load balancer.\n- Concurrency is determined by the [maximum concurrent requests per instance](/run/docs/about-concurrency) for messages. In streaming, each stream is counted once against the maximum concurrent requests.\n\nListening for gRPC requests in a Cloud Run service\n--------------------------------------------------\n\nThe only special requirement for a gRPC server running in\nCloud Run is to listen at the port specified by the `PORT`\nenvironment variable as shown in the following code:\n\n\n### Go\n\n func main() {\n \tlog.Printf(\"grpc-ping: starting server...\")\n\n \tport := os.Getenv(\"PORT\")\n \tif port == \"\" {\n \t\tport = \"8080\"\n \t\tlog.Printf(\"Defaulting to port %s\", port)\n \t}\n\n \tlistener, err := net.Listen(\"tcp\", \":\"+port)\n \tif err != nil {\n \t\tlog.Fatalf(\"net.Listen: %v\", err)\n \t}\n\n \tgrpcServer := grpc.NewServer()\n \tpb.RegisterPingServiceServer(grpcServer, &pingService{})\n \tif err = grpcServer.Serve(listener); err != nil {\n \t\tlog.Fatal(err)\n \t}\n }\n\n\u003cbr /\u003e\n\nOpening a gRPC connection to a service\n--------------------------------------\n\nTo open a gRPC connection to a service so you can send gRPC messages, you need\nto specify the host domain, which is the URL of the Cloud Run service\nor the custom domain [mapped](/run/docs/mapping-custom-domains) to that service,\nalong with the port 443, which is the port expected to be used by gRPC.\n\n\n### Go\n\n\n import (\n \t\"crypto/tls\"\n \t\"crypto/x509\"\n\n \t\"google.golang.org/grpc\"\n \t\"google.golang.org/grpc/credentials\"\n )\n\n // NewConn creates a new gRPC connection.\n // host should be of the form domain:port, e.g., example.com:443\n func NewConn(host string, insecure bool) (*grpc.ClientConn, error) {\n \tvar opts []grpc.DialOption\n \tif host != \"\" {\n \t\topts = append(opts, grpc.WithAuthority(host))\n \t}\n\n \tif insecure {\n \t\topts = append(opts, grpc.WithInsecure())\n \t} else {\n \t\t// Note: On the Windows platform, use of x509.SystemCertPool() requires\n \t\t// Go version 1.18 or higher.\n \t\tsystemRoots, err := x509.SystemCertPool()\n \t\tif err != nil {\n \t\t\treturn nil, err\n \t\t}\n \t\tcred := credentials.NewTLS(&tls.Config{\n \t\t\tRootCAs: systemRoots,\n \t\t})\n \t\topts = append(opts, grpc.WithTransportCredentials(cred))\n \t}\n\n \treturn grpc.Dial(host, opts...)\n }\n\n\u003cbr /\u003e\n\nSending gRPC requests without authentication\n--------------------------------------------\n\nThe following sample shows how to send a request without authentication, using\na [gRPC connection](#connect) configured as mentioned previously.\n\n\n### Go\n\n\n import (\n \t\"context\"\n \t\"time\"\n\n \tpb \"github.com/GoogleCloudPlatform/golang-samples/run/grpc-ping/pkg/api/v1\"\n \t\"google.golang.org/grpc\"\n )\n\n // pingRequest sends a new gRPC ping request to the server configured in the connection.\n func pingRequest(conn *grpc.ClientConn, p *pb.Request) (*pb.Response, error) {\n \tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n \tdefer cancel()\n\n \tclient := pb.NewPingServiceClient(conn)\n \treturn client.Send(ctx, p)\n }\n\n\u003cbr /\u003e\n\nSending gRPC requests with authentication\n-----------------------------------------\n\nThe following sample shows how to use authentication between services, if the\ncalling service has invoker permission to the receiving service. Notice that\nthis code creates an authorization header that has the proper identity token:\nthis is required. The required permissions and the authorization header are\ndescribed in detail in\n[service to service authentication](/run/docs/authenticating/service-to-service).\n\n\n### Go\n\n\n import (\n \t\"context\"\n \t\"fmt\"\n \t\"time\"\n\n \t\"google.golang.org/api/idtoken\"\n \t\"google.golang.org/grpc\"\n \tgrpcMetadata \"google.golang.org/grpc/metadata\"\n\n \tpb \"github.com/GoogleCloudPlatform/golang-samples/run/grpc-ping/pkg/api/v1\"\n )\n\n // pingRequestWithAuth mints a new Identity Token for each request.\n // This token has a 1 hour expiry and should be reused.\n // audience must be the auto-assigned URL of a Cloud Run service or HTTP Cloud Function without port number.\n func pingRequestWithAuth(conn *grpc.ClientConn, p *pb.Request, audience string) (*pb.Response, error) {\n \tctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)\n \tdefer cancel()\n\n \t// Create an identity token.\n \t// With a global TokenSource tokens would be reused and auto-refreshed at need.\n \t// A given TokenSource is specific to the audience.\n \ttokenSource, err := idtoken.NewTokenSource(ctx, audience)\n \tif err != nil {\n \t\treturn nil, fmt.Errorf(\"idtoken.NewTokenSource: %w\", err)\n \t}\n \ttoken, err := tokenSource.Token()\n \tif err != nil {\n \t\treturn nil, fmt.Errorf(\"TokenSource.Token: %w\", err)\n \t}\n\n \t// Add token to gRPC Request.\n \tctx = grpcMetadata.AppendToOutgoingContext(ctx, \"authorization\", \"Bearer \"+token.AccessToken)\n\n \t// Send the request.\n \tclient := pb.NewPingServiceClient(conn)\n \treturn client.Send(ctx, p)\n }\n\n\u003cbr /\u003e\n\nSample code for gRPC streaming\n------------------------------\n\nFor sample code, refer to the `RouteGuide` implementation in the\n[gRPC](https://grpc.io/) Basics tutorial for the\nlanguage of your choice. When using Go, for example, refer to\n[Implementing RouteGuide](https://grpc.io/docs/languages/go/basics/#implementing-routeguide)."]]