Rechercher

Ce contenu n'est pas disponible dans la langue sélectionnée.

Chapter 40. gRPC

download PDF

Since Camel 2.19

Both producer and consumer are supported

The gRPC component allows you to call or expose Remote Procedure Call (RPC) services using Protocol Buffers (protobuf) exchange format over HTTP/2 transport.

40.1. Dependencies

When using grpc with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:

<dependency>
  <groupId>org.apache.camel.springboot</groupId>
  <artifactId>camel-grpc-starter</artifactId>
</dependency>

40.2. URI format

grpc:host:port/service[?options]

40.3. Configuring Options

Camel components are configured on two separate levels:

  • component level
  • endpoint level

40.3.1. Configuring component options

The component level is the highest level which holds general and common configurations that are inherited by the endpoints. For example a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

Configuring components can be done with the Component DSL, in a configuration file (application.properties|yaml), or directly with Java code.

40.3.2. Configuring endpoint options

Where you find yourself configuring the most is on endpoints, as endpoints often have many options, which allows you to configure what you need the endpoint to do. The options are also categorized into whether the endpoint is used as consumer (from) or as a producer (to), or used for both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders, which allows to not hardcode urls, port numbers, sensitive information, and other settings. In other words placeholders allows to externalize the configuration from your code, and gives more flexibility and reuse.

The following two sections lists all the options, firstly for the component followed by the endpoint.

40.4. Component Options

The gRPC component supports 3 options, which are listed below.

NameDescriptionDefaultType

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

40.5. Endpoint Options

The gRPC endpoint is configured using URI syntax:

grpc:host:port/service

with the following path and query parameters:

40.5.1. Path Parameters (3 parameters)

NameDescriptionDefaultType

host (common)

Required The gRPC server host name. This is localhost or 0.0.0.0 when being a consumer or remote server host name when using producer.

 

String

port (common)

Required The gRPC local or remote server port.

 

int

service (common)

Required Fully qualified service name from the protocol buffer descriptor file (package dot service definition name).

 

String

40.5.2. Query Parameters (29 parameters)

NameDescriptionDefaultType

flowControlWindow (common)

The HTTP/2 flow control window size (MiB).

1048576

int

maxMessageSize (common)

The maximum message size allowed to be received/sent (MiB).

4194304

int

autoDiscoverServerInterceptors (consumer)

Setting the autoDiscoverServerInterceptors mechanism, if true, the component will look for a ServerInterceptor instance in the registry automatically otherwise it will skip that checking.

true

boolean

consumerStrategy (consumer)

This option specifies the top-level strategy for processing service requests and responses in streaming mode. If an aggregation strategy is selected, all requests will be accumulated in the list, then transferred to the flow, and the accumulated responses will be sent to the sender. If a propagation strategy is selected, request is sent to the stream, and the response will be immediately sent back to the sender.

Enum values:

  • AGGREGATION
  • PROPAGATION

PROPAGATION

GrpcConsumerStrategy

forwardOnCompleted (consumer)

Determines if onCompleted events should be pushed to the Camel route.

false

boolean

forwardOnError (consumer)

Determines if onError events should be pushed to the Camel route. Exceptions will be set as message body.

false

boolean

maxConcurrentCallsPerConnection (consumer)

The maximum number of concurrent calls permitted for each incoming server connection.

2147483647

int

routeControlledStreamObserver (consumer)

Lets the route to take control over stream observer. If this value is set to true, then the response observer of gRPC call will be set with the name GrpcConstants.GRPC_RESPONSE_OBSERVER in the Exchange object. Please note that the stream observer’s onNext(), onError(), onCompleted() methods should be called in the route.

false

boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

 

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly
  • InOut
 

ExchangePattern

autoDiscoverClientInterceptors (producer)

Setting the autoDiscoverClientInterceptors mechanism, if true, the component will look for a ClientInterceptor instance in the registry automatically otherwise it will skip that checking.

true

boolean

method (producer)

gRPC method name.

 

String

producerStrategy (producer)

The mode used to communicate with a remote gRPC server. In SIMPLE mode a single exchange is translated into a remote procedure call. In STREAMING mode all exchanges will be sent within the same request (input and output of the recipient gRPC service must be of type 'stream').

Enum values:

  • SIMPLE
  • STREAMING

SIMPLE

GrpcProducerStrategy

streamRepliesTo (producer)

When using STREAMING client mode, it indicates the endpoint where responses should be forwarded.

 

String

userAgent (producer)

The user agent header passed to the server.

 

String

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

synchronous (advanced)

Sets whether synchronous processing should be strictly used.

false

boolean

authenticationType (security)

Authentication method type in advance to the SSL/TLS negotiation.

Enum values:

  • NONE
  • GOOGLE
  • JWT

NONE

GrpcAuthType

jwtAlgorithm (security)

JSON Web Token sign algorithm.

Enum values:

  • HMAC256
  • HMAC384
  • HMAC512

HMAC256

JwtAlgorithm

jwtIssuer (security)

JSON Web Token issuer.

 

String

jwtSecret (security)

JSON Web Token secret.

 

String

jwtSubject (security)

JSON Web Token subject.

 

String

keyCertChainResource (security)

The X.509 certificate chain file resource in PEM format link.

 

String

keyPassword (security)

The PKCS#8 private key file password.

 

String

keyResource (security)

The PKCS#8 private key file resource in PEM format link.

 

String

negotiationType (security)

Identifies the security negotiation type used for HTTP/2 communication.

Enum values:

  • TLS
  • PLAINTEXT_UPGRADE
  • PLAINTEXT

PLAINTEXT

NegotiationType

serviceAccountResource (security)

Service Account key file in JSON format resource link supported by the Google Cloud SDK.

 

String

trustCertCollectionResource (security)

The trusted certificates collection file resource in PEM format for verifying the remote endpoint’s certificate.

 

String

40.6. Message Headers

The gRPC component supports 3 message header(s), which is/are listed below:

NameDescriptionDefaultType

CamelGrpcMethodName (consumer)

Constant: GRPC_METHOD_NAME_HEADER

Method name handled by the consumer service.

 

String

CamelGrpcUserAgent (consumer)

Constant: GRPC_USER_AGENT_HEADER

If provided, the given agent will prepend the gRPC library’s user agent information.

 

String

CamelGrpcEventType (consumer)

Constant: GRPC_EVENT_TYPE_HEADER

Received event type from the sent request. Possible values: onNext onCompleted onError.

 

String

40.7. Transport security and authentication support

The following authentication mechanisms are built-in to gRPC and available in this component:

  • SSL/TLS: gRPC has SSL/TLS integration and promotes the use of SSL/TLS to authenticate the server, and to encrypt all the data exchanged between the client and the server. Optional mechanisms are available for clients to provide certificates for mutual authentication.
  • Token-based authentication with Google: gRPC provides a generic mechanism to attach metadata based credentials to requests and responses. Additional support for acquiring access tokens while accessing Google APIs through gRPC is provided. In general this mechanism must be used as well as SSL/TLS on the channel.

To enable these features the following component properties combinations must be configured:

Num.OptionParameterValueRequired/Optional

1

SSL/TLS

negotiationType

TLS

Required

  

keyCertChainResource

 

Required

  

keyResource

 

Required

  

keyPassword

 

Optional

  

trustCertCollectionResource

 

Optional

2

Token-based authentication with Google API

authenticationType

GOOGLE

Required

  

negotiationType

TLS

Required

  

serviceAccountResource

 

Required

3

Custom JSON Web Token implementation authentication

authenticationType

JWT

Required

  

negotiationType

NONE or TLS

Optional. The TLS/SSL not checking for this type, but strongly recommended.

  

jwtAlgorithm

HMAC256(default) or (HMAC384,HMAC512)

Optional

  

jwtSecret

 

Required

  

jwtIssuer

 

Optional

  

jwtSubject

 

Optional

40.8. gRPC producer resource type mapping

The table below shows the types of objects in the message body, depending on the types (simple or stream) of incoming and outgoing parameters, as well as the invocation style (synchronous or asynchronous). Please note, that invocation of the procedures with incoming stream parameter in asynchronous style are not allowed.

Invocation styleRequest typeResponse typeRequest Body TypeResult Body Type

synchronous

simple

simple

Object

Object

synchronous

simple

stream

Object

List<Object>

synchronous

stream

simple

not allowed

not allowed

synchronous

stream

stream

not allowed

not allowed

asynchronous

simple

simple

Object

List<Object>

asynchronous

simple

stream

Object

List<Object>

asynchronous

stream

simple

Object or List<Object>

List<Object>

asynchronous

stream

stream

Object or List<Object>

List<Object>

40.9. Examples

Below is a simple synchronous method invoke with host and port parameters:

from("direct:grpc-sync")
.to("grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=sendPing&synchronous=true");
<route>
    <from uri="direct:grpc-sync" />
    <to uri="grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=sendPing&synchronous=true"/>
</route>

An asynchronous method invokes

from("direct:grpc-async")
.to("grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=pingAsyncResponse");

a gRPC service consumer with propagation consumer strategy:

from("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?consumerStrategy=PROPAGATION")
.to("direct:grpc-service");

gRPC service producer with streaming producer strategy (requires a service that uses "stream" mode as input and output):

from("direct:grpc-request-stream")
.to("grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=PingAsyncAsync&producerStrategy=STREAMING&streamRepliesTo=direct:grpc-response-stream");

from("direct:grpc-response-stream")
.log("Response received: ${body}");

gRPC service consumer TLS/SSL security negotiation enabled:

from("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?consumerStrategy=PROPAGATION&negotiationType=TLS&keyCertChainResource=file:src/test/resources/certs/server.pem&keyResource=file:src/test/resources/certs/server.key&trustCertCollectionResource=file:src/test/resources/certs/ca.pem")
.to("direct:tls-enable")

gRPC service producer with custom JSON Web Token (JWT) implementation authentication:

from("direct:grpc-jwt")
.to("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?method=pingSyncSync&synchronous=true&authenticationType=JWT&jwtSecret=supersecuredsecret");

40.10. Configuration

Use the protobuf-maven-plugin, which calls the Protocol Buffer Compiler (protoc) to generate Java source files from .proto (protocol buffer definition) files. This plugin will generate procedures request and response classes, their builders and gRPC procedures stubs classes as well.

Following steps are required:

Insert operating system and CPU architecture detection extension inside <build> tag of the project pom.xml or set $\{os.detected.classifier} parameter manually

<extensions>
  <extension>
    <groupId>kr.motd.maven</groupId>
    <artifactId>os-maven-plugin</artifactId>
    <version>1.7.1</version>
  </extension>
</extensions>

Insert the gRPC and protobuf Java code generator plugins into the <plugins> tag of the project’s pom.xml.

<plugin>
  <groupId>org.xolstice.maven.plugins</groupId>
  <artifactId>protobuf-maven-plugin</artifactId>
  <version>0.6.1</version>
  <configuration>
    <protocArtifact>com.google.protobuf:protoc:${protobuf-version}:exe:${os.detected.classifier}</protocArtifact>
    <pluginId>grpc-java</pluginId>
    <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc-version}:exe:${os.detected.classifier}</pluginArtifact>
  </configuration>
  <executions>
    <execution>
      <goals>
        <goal>compile</goal>
        <goal>compile-custom</goal>
        <goal>test-compile</goal>
        <goal>test-compile-custom</goal>
      </goals>
    </execution>
  </executions>
</plugin>

40.11. Additional resources

See these resources:

40.12. Spring Boot Auto-Configuration

The component supports 4 options, which are listed below.

NameDescriptionDefaultType

camel.component.grpc.autowired-enabled

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

Boolean

camel.component.grpc.bridge-error-handler

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

Boolean

camel.component.grpc.enabled

Whether to enable auto configuration of the grpc component. This is enabled by default.

 

Boolean

camel.component.grpc.lazy-start-producer

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

Boolean

Red Hat logoGithubRedditYoutubeTwitter

Apprendre

Essayez, achetez et vendez

Communautés

À propos de la documentation Red Hat

Nous aidons les utilisateurs de Red Hat à innover et à atteindre leurs objectifs grâce à nos produits et services avec un contenu auquel ils peuvent faire confiance.

Rendre l’open source plus inclusif

Red Hat s'engage à remplacer le langage problématique dans notre code, notre documentation et nos propriétés Web. Pour plus de détails, consultez leBlog Red Hat.

À propos de Red Hat

Nous proposons des solutions renforcées qui facilitent le travail des entreprises sur plusieurs plates-formes et environnements, du centre de données central à la périphérie du réseau.

© 2024 Red Hat, Inc.