Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En esta página, se muestran detalles específicos de Knative serving para desarrolladores que desean usar gRPC para conectar un servicio de Knative serving con otros servicios, por ejemplo, para proporcionar una comunicación simple y de alto rendimiento entre microservicios internos. Knative serving admite llamadas de gRPC unarias y de transmisión.
gRPC unario
En una llamada RPC unaria, el cliente envía una sola solicitud al servidor y obtiene una sola respuesta, similar a una llamada a función normal:
Las siguientes opciones de transmisión están disponibles con gRPC.
RPC de transmisión del servidor en las que el cliente envía una solicitud al servidor y obtiene una transmisión para leer que contiene una secuencia de mensajes. El cliente lee la transmisión que se muestra hasta que no haya más mensajes.
RPC de transmisión del cliente en las que el cliente escribe una secuencia de mensajes y los envía al servidor en una transmisión. Una vez que el cliente termina de escribir los mensajes, espera a que el servidor muestre la respuesta.
RPC de transmisión bidireccional en las que el cliente y el servidor envían mensajes en dos transmisiones de lectura y escritura que operan de forma independiente.
Entre los casos prácticos, se incluyen los siguientes:
Comunicación entre microservicios internos
Cargas altas de datos (gRPC usa búferes de protocolo, que son hasta siete veces más rápidos que las llamadas de REST).
Solo se necesita una definición de servicio simple; no es necesario que escribas una biblioteca cliente completa
Para integrar el servicio a gRPC, sigue estos pasos:
Define los mensajes y las respuestas de la solicitud en un archivo proto y compílalos.
Crea un servidor de gRPC para administrar las solicitudes y mostrar las respuestas: debe escuchar la variable de entorno PORT.
Crea un cliente que envíe solicitudes y administre respuestas desde el servidor de gRPC.
De manera opcional, agrega autenticación.
Compila y, luego, implementa el servicio.
Define y compila mensajes en un archivo proto
No hay elementos adicionales ni específicos de Knative serving para agregar a las definiciones de proto. Como con cualquier otro uso de gRPC, usa búferes de protocolo de gRPC para las definiciones de servicios y la serialización de datos.
Crea un cliente de gRPC
No hay elementos adicionales ni específicos de Knative serving para agregar a un cliente que usa gRPC. Sigue los documentos de gRPC acerca del uso de definiciones de servicios en el código del cliente y los clientes de muestra proporcionados en los instructivos de gRPC específicos del lenguaje.
Escucha las solicitudes de gRPC en un servicio de Knative serving
El único requisito especial para un servidor de gRPC que se ejecuta en Knative serving es escuchar en el puerto que la variable de entorno PORT especificó como se muestra en el código:
Go
func main() {
log.Printf("grpc-ping: starting server...")
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s", port)
}
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Fatalf("net.Listen: %v", err)
}
grpcServer := grpc.NewServer()
pb.RegisterPingServiceServer(grpcServer, &pingService{})
if err = grpcServer.Serve(listener); err != nil {
log.Fatal(err)
}
}
Abre una conexión de gRPC a un servicio
Para abrir una conexión de gRPC a un servicio a fin de que puedas enviar mensajes de gRPC, debes especificar el dominio del host, que es la URL del servicio de Knative serving o el dominio personalizado que se asignó a ese servicio, junto con el puerto 443, que es el que se espera que use 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:443
func NewConn(host string, insecure bool) (*grpc.ClientConn, error) {
var opts []grpc.DialOption
if host != "" {
opts = append(opts, grpc.WithAuthority(host))
}
if insecure {
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()
if err != nil {
return nil, err
}
cred := credentials.NewTLS(&tls.Config{
RootCAs: systemRoots,
})
opts = append(opts, grpc.WithTransportCredentials(cred))
}
return grpc.Dial(host, opts...)
}
Envía solicitudes de gRPC sin autenticación
En el siguiente ejemplo, se muestra cómo enviar una solicitud sin autenticación mediante una conexión de gRPC que se configuró como se mencionó antes.
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.
func pingRequest(conn *grpc.ClientConn, p *pb.Request) (*pb.Response, error) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
client := pb.NewPingServiceClient(conn)
return client.Send(ctx, p)
}
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2024-08-22 (UTC)"],[],[],null,["# Invoking with gRPC\n\nThis page shows Knative serving-specific details for developers who\nwant to use [gRPC](https://grpc.io/) to connect a\nKnative serving service with other services, for example, to provide\nsimple, high performance communication between internal\nmicroservices. Knative serving supports both\n[unary](#before-you-begin)\nand\n[streaming](#before-you-begin)\ngRPC calls. \n\n### gRPC Unary\n\nIn a unary RPC call, the client sends a single request to the server and gets a single response back, similar to a normal function call: \n\n```\nrpc SayHello(HelloRequest) returns (HelloResponse);\n``` \nOK \n\n### gRPC Streaming\n\n\u003cbr /\u003e\n\nThe following streaming options are available with gRPC.\nServer streaming RPCs where the client sends a request to the server and gets a\nstream to read containing a sequence of messages. The client reads the returned\nstream until there are no more messages. \n\n```\nrpc LotsOfReplies(HelloRequest) returns (stream HelloResponse);\n```\n\n\u003cbr /\u003e\n\nClient streaming RPCs where the client writes a sequence of messages and sends\nthem to the server in a stream. After the client finishes writing messages, it\nwaits for the server to return its response. \n\n```\nrpc LotsOfGreetings(stream HelloRequest) returns (HelloResponse);\n```\n\n\u003cbr /\u003e\n\nBidirectional streaming RPCs where client and server send messages in two\nread-write streams that operate independently. \n\n```\nrpc BidiHello(stream HelloRequest) returns (stream HelloResponse);\n``` \nOK\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\nTo integrate your service with gRPC,\n\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\nDefining and compiling messages in a proto file\n-----------------------------------------------\n\nThere are no extra or Knative serving 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 Knative serving 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\nListening for gRPC requests in a Knative serving service\n--------------------------------------------------------\n\nThe only special requirement for a gRPC server running in\nKnative serving is to listen at the port specified by the `PORT`\nenvironment variable as shown in the 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 Knative serving service\nor the custom domain [mapped](/kubernetes-engine/enterprise/knative-serving/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"]]