gRPC

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.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-grpc</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

gRCP requires strong own of the Google Guava version. It’s necessary to add following configuration property to the maven file

<properties>
    <google-guava-version>${grpc-guava-version}</google-guava-version>
<properties>

URI format

grpc://service[?options]

Endpoint Options

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

Name Description Default Type

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

The gRPC endpoint is configured using URI syntax:

grpc:host:port/service

with the following path and query parameters:

Path Parameters (3 parameters):

Name Description Default Type

host

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

Required The gRPC local or remote server port

int

service

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

String

Query Parameters (28 parameters):

Name Description Default Type

autoDiscoverClientInterceptors (common)

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

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

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

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. There are 2 enums and the value can be one of: 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

maxConcurrentCallsPer​Connection (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

exceptionHandler (consumer)

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)

Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut

ExchangePattern

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

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'). There are 2 enums and the value can be one of: 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

synchronous (advanced)

Sets whether synchronous processing should be strictly used

false

boolean

authenticationType (security)

Authentication method type in advance to the SSL/TLS negotiation. There are 3 enums and the value can be one of: NONE, GOOGLE, JWT

NONE

GrpcAuthType

jwtAlgorithm (security)

JSON Web Token sign algorithm. There are 3 enums and the value can be one of: 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. There are 3 enums and the value can be one of: 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

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. Option Parameter Value Required/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

TLS with OpenSSL is currently the recommended approach for using gRPC over TLS component. Using the JDK for ALPN is generally much slower and may not support the necessary ciphers for HTTP2. This function is not implemented in the component.

There might be a need to install additional libraries according to the Operating System of choice. For more information consult the Security page of gRPC.

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 style Request type Response type Request Body Type Result 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>

gRPC consumer headers (will be installed after the consumer invocation)

Header name Description Possible values

CamelGrpcMethodName

Method name handled by the consumer service

CamelGrpcEventType

Received event type from the sent request

onNext, onCompleted or onError

CamelGrpcUserAgent

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

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 invoke

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

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/SLL security negotiation enable

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 implementation authentication

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

Configuration

It’s it is recommended to use Maven Protocol Buffers Plugin which calls Protocol Buffer Compiler (protoc) tool to generate Java source files from .proto (protocol buffer definition) files for the custom project. 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.4.1.Final</version>
  </extension>
</extensions>

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

<plugin>
  <groupId>org.xolstice.maven.plugins</groupId>
  <artifactId>protobuf-maven-plugin</artifactId>
  <version>0.5.0</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>

For more information, see these resources

Spring Boot Auto-Configuration

When using grpc with 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>
  <version>x.x.x</version>
  <!-- use the same version as your Camel core version -->
</dependency>

The component supports 4 options, which are listed below.

Name Description Default Type

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