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> Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
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.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or 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.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The gRPC component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. 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 | |
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 | |
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 |
Endpoint Options
The gRPC endpoint is configured using URI syntax:
grpc:host:port/service
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The host name or IP address. For the consumer, the address that the gRPC server binds to, such as localhost or 0.0.0.0. For the producer, the host of the remote gRPC server. | String | ||
Required The port. For the consumer, the port that the gRPC server listens on, where 0 lets the operating system choose a free port. For the producer, the port of the remote gRPC server. | int | ||
Required The fully qualified name of the gRPC service: the Java package of the classes generated from the .proto file, a dot, and the service name, for example org.apache.camel.component.grpc.PingPong. The component loads the generated class of the service (PingPongGrpc in the example) by this name. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The HTTP/2 flow control window size in bytes of the producer. The consumer uses initialFlowControlWindow instead. | 1048576 | int | |
Whether to route an exchange without a body, with the CamelGrpcEventType header set to onCompleted, when a stream completes. The consumer does it for client and bidirectional streaming calls with the PROPAGATION or DELEGATION strategy, and the producer to the streamRepliesTo endpoint. | false | boolean | |
Whether to route an exchange with the Throwable as body, and the CamelGrpcEventType header set to onError, when a stream fails. The consumer does it for client and bidirectional streaming calls with the PROPAGATION or DELEGATION strategy, and the producer to the streamRepliesTo endpoint. | false | boolean | |
The maximum size in bytes of a message that the consumer or the producer receives. A larger message fails the call with the RESOURCE_EXHAUSTED status. | 4194304 | int | |
Whether the consumer intercepts the incoming calls with all the io.grpc.ServerInterceptor beans of the registry. | true | boolean | |
How the consumer handles client streaming and bidirectional streaming calls; unary and server streaming calls always give one exchange per call. AGGREGATION routes all request messages as one List when the client completes the stream, and sends the reply of the route. PROPAGATION routes each request message in its own exchange and sends its reply, unless routeControlledStreamObserver is true. DELEGATION routes each request message and sends nothing: it requires routeControlledStreamObserver. Enum values:
| PROPAGATION | GrpcConsumerStrategy | |
The initial HTTP/2 flow control window size in bytes of the consumer. The consumer then adjusts the window to the bandwidth-delay product of the connection. | 1048576 | int | |
The time in milliseconds without received data after which the consumer sends a keepalive ping to the client. A value of 1000 days or more disables keepalive. | 7200000 | long | |
The time in milliseconds that the consumer waits for the reply to a keepalive ping before it closes the connection. | 20000 | long | |
The maximum number of concurrent calls permitted for each incoming server connection. Defaults to no limit. | 2147483647 | int | |
The maximum time in milliseconds that a connection exists before the consumer closes it gracefully, with a random jitter of +/-10%. A value of 1000 days or more, such as the default, means no limit. | 9223372036854776000 | long | |
The time in milliseconds that the calls in progress have to complete once maxConnectionAge is reached, before the consumer cancels them and closes the connection. A value of 1000 days or more, such as the default, means no limit. | 9223372036854776000 | long | |
The time in milliseconds without outstanding calls after which the consumer closes a connection gracefully. A value of 1000 days or more, such as the default, means no limit. | 9223372036854776000 | long | |
The maximum size in bytes of the metadata (the headers) of a call that the consumer receives. | 8192 | int | |
The maximum number of RST_STREAM frames that the consumer accepts from a connection per maxRstPeriodSeconds, before it closes the connection. Set it together with maxRstPeriodSeconds: the consumer fails to start if only one of them is greater than 0. 0 means no limit. | 0 | int | |
The period in seconds of maxRstFramesPerWindow. Set it together with maxRstFramesPerWindow: the consumer fails to start if only one of them is greater than 0. 0 means no limit. | 0 | int | |
Whether the consumer leaves out the exception message from the status description that it sends to the client when the exchange fails. The description is then Exchange processing failed, and the status is INTERNAL in both cases. | true | boolean | |
The shortest time in milliseconds between keepalive pings that the consumer permits a client. The consumer closes the connection of a client that sends pings more often. | 300000 | long | |
Whether the consumer permits clients to send keepalive pings (HTTP/2 PING frames) on a connection without outstanding calls. | false | boolean | |
Whether the route sends the responses instead of the consumer. The consumer sets the response StreamObserver of the call as the grpcResponseObserver exchange property, and the route replies with a producer with toRouteControlledStreamObserver=true. Not compatible with the AGGREGATION strategy. | false | boolean | |
Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. 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 | |
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 | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
Whether the producer intercepts the outgoing calls with all the io.grpc.ClientInterceptor beans of the registry. | true | boolean | |
Whether the exchanges that the producer sends to the streamRepliesTo endpoint get a copy of the exchange properties of the exchange that made the call. For example, the replies then keep the grpcResponseObserver property for toRouteControlledStreamObserver. | false | boolean | |
The name of the method that the producer calls, as in the .proto file or as the Java method name. The producer converts it to the lowerCamelCase name of the stub method, so SendPing and send_ping both call sendPing. | String | ||
How the producer calls the method. SIMPLE makes one call per exchange. STREAMING sends the body of each exchange as a message on one shared call, which needs a method with a stream request, and sends the responses to the streamRepliesTo endpoint. Enum values:
| SIMPLE | GrpcProducerStrategy | |
The URI of the endpoint that receives the responses of the server, one exchange per response message, with the CamelGrpcEventType header. Required with the STREAMING strategy. With the SIMPLE strategy the responses go to this endpoint instead of the body, unless synchronous is true. | String | ||
Whether the producer replies to the client of a consumer with routeControlledStreamObserver=true, instead of calling a server. It sends the body to the StreamObserver in the grpcResponseObserver exchange property, as the event in the CamelGrpcEventType header. The other options of the producer are not used. | false | boolean | |
The user agent that the producer sends to the server. gRPC Java adds its own user agent after this value. | String | ||
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 | |
Whether to process synchronously. The producer then calls the method with a blocking stub and waits for the response, which methods with a stream request do not support. The consumer then routes unary and server streaming calls synchronously. | false | boolean | |
The authentication of the calls, in addition to the transport security. GOOGLE makes the producer send the OAuth2 access tokens of the Google service account in serviceAccountResource, and requires negotiationType TLS. GOOGLE is supported only on the producer: a consumer with GOOGLE fails to start. JWT makes the producer send a JSON Web Token signed with jwtSecret, and the consumer accept only calls with a valid token. Enum values:
| NONE | GrpcAuthType | |
The HMAC algorithm that signs the JSON Web Token on the producer and verifies it on the consumer. Enum values:
| HMAC256 | JwtAlgorithm | |
The issuer (iss claim) of the JSON Web Token. The producer puts it in the token, and the consumer accepts only tokens with the same issuer. | String | ||
The maximum age of a JSON Web Token that the consumer accepts, in milliseconds, from its iat (issued at) claim. When set, the consumer rejects tokens that are older, or that have no iat claim. The consumer always rejects a token whose exp (expires at) claim has passed. The default 0 does not check the age, so tokens without an exp claim are valid until jwtSecret changes. Used when authenticationType is JWT. | long | ||
The secret key of the HMAC algorithm that signs the JSON Web Token on the producer and verifies it on the consumer. Required when authenticationType is JWT. | String | ||
The subject (sub claim) of the JSON Web Token. The producer puts it in the token, and the consumer accepts only tokens with the same subject. | String | ||
How long a JSON Web Token that the producer sends is valid, in milliseconds: the token has the iat (issued at) claim and an exp (expires at) claim this much later. The producer creates a new token when less than a tenth of the lifetime, at most one minute, is left. A value of 0 sends a token without iat and exp claims, which is valid until jwtSecret changes. Used when authenticationType is JWT. | 3600000 | long | |
The location of the X.509 certificate chain in PEM format. For the consumer, the certificate of the server, required with TLS. For the producer, the certificate of the client for mutual TLS, set together with keyResource. | String | ||
The password of the private key in keyResource, if the key is encrypted. | String | ||
The location of the PKCS#8 private key in PEM format of keyCertChainResource. For the consumer, the key of the server, required with TLS. For the producer, the key of the client for mutual TLS, set together with keyCertChainResource. | String | ||
The transport security of the HTTP/2 connection: PLAINTEXT for no encryption, or TLS. With TLS the consumer requires keyCertChainResource and keyResource, and a certificate from each client. Enum values:
| PLAINTEXT | NegotiationType | |
The location of the Google Cloud service account key file in JSON format, for example classpath:service-account.json. Required when authenticationType is GOOGLE: the producer sends the OAuth2 access tokens of this account. | String | ||
The location of the trusted certificates in PEM format that verify the certificate of the other side: of the server for the producer, of the clients for the consumer. For the consumer, these are the CA certificates whose client certificates the consumer accepts, required with TLS. If not set, the producer verifies the server with the default trust store of the JVM. | String |
Message Headers
The gRPC component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
CamelGrpcMethodName (consumer) Constant: | The name of the method that the client called, as the Java method name in lowerCamelCase, for example sendPing. The consumer sets it. | String | |
| Constant: | The user agent of the client that made the call, from the user-agent header of the request. The consumer sets it. | String | |
| Constant: | The event of the stream: onNext for a message, onCompleted when the stream completes, or onError when it fails. The consumer sets it for client and bidirectional streaming calls, and the producer on the exchanges that it sends to streamRepliesTo. The STREAMING producer and a producer with toRouteControlledStreamObserver read it to select the event to send. | String |
Message Body
The message body at each side of the gRPC component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| The protobuf request message of the called method, with the method name in the CamelGrpcMethodName header. A streaming request gives one exchange per message, or with the AGGREGATION strategy a List of all its messages. forwardOnCompleted sends no body at the end of the stream, forwardOnError the Throwable.
|
Consumer reply |
| The protobuf response message of the method, or a List of them for a streaming response; no body sends an empty message. Another type is converted to the response message, or the call ends with an INTERNAL error: text, bytes, a Map or the unchanged request fail, build the message of the method. With routeControlledStreamObserver the route replies through a producer with toRouteControlledStreamObserver. Not known when |
Producer input |
| The protobuf request message of the method, or a List of them for a streaming request. Text, bytes or a Map fail with an argument type mismatch: build the message first. |
Producer output |
| A List of the protobuf response messages. With synchronous=true the response message itself, or a List of them for a streaming response. With the STREAMING strategy the body is unchanged and each response goes to the streamRepliesTo endpoint.
|
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Usage
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. This mechanism is supported only on the producer: a consumer with
authenticationType=GOOGLEfails to start, as the consumer has no check of these tokens. To authenticate the clients of a consumer, use JWT or mutual TLS.
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 on a consumer. Optional on a producer: only for mutual TLS, together with keyResource | |||
keyResource | Required on a consumer. Optional on a producer: only for mutual TLS, together with keyCertChainResource | |||
keyPassword | Optional | |||
trustCertCollectionResource | Required on a consumer: the CA certificates whose client certificates the consumer accepts. Optional on a producer: when not set, a producer verifies the server with the default trust store of the JVM | |||
2 | Token-based authentication with Google API (producer only) | authenticationType | Required | |
negotiationType | TLS | Required | ||
serviceAccountResource | Required | |||
3 | Custom JSON Web Token implementation authentication | authenticationType | JWT | Required |
negotiationType | PLAINTEXT or TLS | Optional, but TLS is strongly recommended: with PLAINTEXT the token is sent in clear text, and whoever reads it can make calls with it until it expires | ||
jwtAlgorithm | HMAC256(default) or (HMAC384,HMAC512) | Optional | ||
jwtSecret | Required | |||
jwtIssuer | Optional | |||
jwtSubject | Optional | |||
jwtTokenLifetime | 1 hour (default) | Optional. On a producer: how long a token is valid (the exp claim). 0 sends a token without expiry | ||
jwtMaxTokenAge | Optional. On a consumer: the maximum age of a token by its iat claim. Not checked by default |
JSON Web Token expiry
With authenticationType=JWT, the producer sends a token with the iat (issued at) and exp (expires at) claims, which is valid for jwtTokenLifetime (1 hour by default). The producer creates a new token when less than a tenth of the lifetime, at most one minute, is left of the current one. With jwtTokenLifetime=0 the producer sends a token without iat and exp, as before Camel 4.24, which is valid until jwtSecret changes.
The consumer rejects a token whose exp claim has passed, and a token whose iat claim is in the future. A clock difference of up to one minute between the hosts is accepted. A token without exp, such as one from another client, is accepted until jwtSecret changes, unless jwtMaxTokenAge is set: then the consumer also rejects a token that is older than jwtMaxTokenAge by its iat claim, or that has no iat claim.
gRPC consumer reply
The message body at the end of the consumer route is the reply to the client: the response message of the called method, or a List of them for a streaming response. A message without a body sends an empty response message.
A body of another type is converted to the response message type with a Camel type converter. When there is no such conversion, nothing is sent, and the call ends with an INTERNAL status error. For example, a route that leaves the request message unchanged fails the call instead of sending the request as the response.
With routeControlledStreamObserver=true the route sends the responses itself, with a producer endpoint with toRouteControlledStreamObserver=true. That producer applies the same conversion to the body of each onNext event (each element of a List body is sent as a message). When a message cannot be converted, nothing is sent, the call ends with an INTERNAL status error and the exchange fails. A redelivery of the exchange fails the same way. The error description is muted unless the consumer has muteException=false. The consumer passes the response message type in the grpcResponseType exchange property and its muteException option in the grpcMuteException exchange property; when grpcResponseType is not on the exchange, the body is sent as is. Once the producer ended the call with an error, it ignores the later events of the call, such as a forwarded onCompleted, as nothing more can be sent to the client. Calls on the StreamObserver from the grpcResponseObserver exchange property in the route’s own code are not checked.
The body of an onError event must be a Throwable, which ends the call. Any other body, or no body, fails the exchange with an IllegalArgumentException; the call still ends with an INTERNAL status error that has the text of the body as description, so the client does not wait until its deadline.
The producer sends the event named by the CamelGrpcEventType header (onNext, onCompleted or onError). The consumer sets this header for the events of client streaming and bidirectional streaming calls, and the reply exchanges of a streamRepliesTo producer have it. When a route calls the producer with an exchange without the header, for example in a unary call, it must set the header itself: without it, or with another value, nothing is sent and the exchange fails with an IllegalArgumentException. An exchange without the grpcResponseObserver exchange property, that did not come from a consumer with routeControlledStreamObserver=true, also fails with an IllegalArgumentException.
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 is 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 Proxy
It is not possible to create a universal proxy-route for all methods, so you need to divide your gRPC service into several services by method’s type: unary, server streaming, client streaming and bidirectional streaming.
Unary
For unary requests, it is enough to write the following code:
-
Java
-
XML
-
YAML
from("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong")
.toD("grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=${header.CamelGrpcMethodName}"); <route>
<from uri="grpc://localhost:1101/org.apache.camel.component.grpc.PingPong"/>
<toD uri="grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=${header.CamelGrpcMethodName}"/>
</route> - route:
from:
uri: grpc://localhost:1101/org.apache.camel.component.grpc.PingPong
steps:
- toD:
uri: grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong
parameters:
method: "${header.CamelGrpcMethodName}" Server streaming
Server streaming may be done by the same approach as unary, but in that configuration Camel route will wait stream for completion and will aggregate all responses to a list before sending that data as response stream. If this behavior is unacceptable, you need to apply a number of options:
-
Set
routeControlledStreamObserver=truefor consumer. Later it will be used to publish responses; -
Set
streamRepliesTooption for producer to handle streaming nature of responses; -
Set forwarding of
onErrorandonCompletedfor producer; -
Set
inheritExchangePropertiesForReplies=trueto inheritStreamObserverobtained on the first step; -
Create another route to process streamed data. That route must contain gRPC-producer step with the only parameter
toRouteControlledStreamObserver=truewhich will publish incoming exchanges as response stream elements.
Example:
-
Java
-
XML
-
YAML
from("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?routeControlledStreamObserver=true")
.toD("grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=${header.CamelGrpcMethodName}&streamRepliesTo=direct:next&forwardOnError=true&forwardOnCompleted=true&inheritExchangePropertiesForReplies=true");
from("direct:next")
.to("grpc://dummy:0/?toRouteControlledStreamObserver=true"); <route>
<from uri="grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?routeControlledStreamObserver=true"/>
<toD uri="grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=${header.CamelGrpcMethodName}&streamRepliesTo=direct:next&forwardOnError=true&forwardOnCompleted=true&inheritExchangePropertiesForReplies=true"/>
</route>
<route>
<from uri="direct:next"/>
<to uri="grpc://dummy:0/?toRouteControlledStreamObserver=true"/>
</route> - route:
from:
uri: grpc://localhost:1101/org.apache.camel.component.grpc.PingPong
parameters:
routeControlledStreamObserver: true
steps:
- toD:
uri: grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong
parameters:
method: "${header.CamelGrpcMethodName}"
streamRepliesTo: direct:next
forwardOnError: true
forwardOnCompleted: true
inheritExchangePropertiesForReplies: true
- route:
from:
uri: direct:next
steps:
- to:
uri: grpc://dummy:0/
parameters:
toRouteControlledStreamObserver: true Client streaming and bidirectional streaming
Both client streaming and bidirectional streaming gRPC methods expose StreamObserver as responses' handler. Therefore, you need the same technique as described in the server streaming section (all 5 steps).
But there is another thing: requests also come in streaming mode. So you need the following:
-
Choose the consumer strategy. With
routeControlledStreamObserver=truethe consumer sends no responses itself with either strategy: the defaultPROPAGATIONroutes the events of a call one at a time, in order, whileDELEGATIONdoes not wait for an event to be done before it routes the next one; -
Forward
onErrorandonCompletionon consumer; -
Set producer strategy to STREAMING.
Example:
-
Java
-
XML
-
YAML
from("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?routeControlledStreamObserver=true&consumerStrategy=DELEGATION&forwardOnError=true&forwardOnCompleted=true")
.toD("grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=${header.CamelGrpcMethodName}&producerStrategy=STREAMING&streamRepliesTo=direct:next&forwardOnError=true&forwardOnCompleted=true&inheritExchangePropertiesForReplies=true");
from("direct:next")
.to("grpc://dummy:0/?toRouteControlledStreamObserver=true"); <route>
<from uri="grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?routeControlledStreamObserver=true&consumerStrategy=DELEGATION&forwardOnError=true&forwardOnCompleted=true"/>
<toD uri="grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=${header.CamelGrpcMethodName}&producerStrategy=STREAMING&streamRepliesTo=direct:next&forwardOnError=true&forwardOnCompleted=true&inheritExchangePropertiesForReplies=true"/>
</route>
<route>
<from uri="direct:next"/>
<to uri="grpc://dummy:0/?toRouteControlledStreamObserver=true"/>
</route> - route:
from:
uri: grpc://localhost:1101/org.apache.camel.component.grpc.PingPong
parameters:
routeControlledStreamObserver: true
consumerStrategy: DELEGATION
forwardOnError: true
forwardOnCompleted: true
steps:
- toD:
uri: grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong
parameters:
method: "${header.CamelGrpcMethodName}"
producerStrategy: STREAMING
streamRepliesTo: direct:next
forwardOnError: true
forwardOnCompleted: true
inheritExchangePropertiesForReplies: true
- route:
from:
uri: direct:next
steps:
- to:
uri: grpc://dummy:0/
parameters:
toRouteControlledStreamObserver: true Examples
Below is a simple synchronous method invoke with host and port parameters
-
Java
-
XML
-
YAML
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> - route:
from:
uri: direct:grpc-sync
steps:
- to:
uri: grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong
parameters:
method: sendPing
synchronous: true An asynchronous method invoke
-
Java
-
XML
-
YAML
from("direct:grpc-async")
.to("grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=pingAsyncResponse"); <route>
<from uri="direct:grpc-async"/>
<to uri="grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=pingAsyncResponse"/>
</route> - route:
from:
uri: direct:grpc-async
steps:
- to:
uri: grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong
parameters:
method: pingAsyncResponse gRPC service consumer with propagation consumer strategy
-
Java
-
XML
-
YAML
from("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?consumerStrategy=PROPAGATION")
.to("direct:grpc-service"); <route>
<from uri="grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?consumerStrategy=PROPAGATION"/>
<to uri="direct:grpc-service"/>
</route> - route:
from:
uri: grpc://localhost:1101/org.apache.camel.component.grpc.PingPong
parameters:
consumerStrategy: PROPAGATION
steps:
- to:
uri: direct:grpc-service gRPC service producer with streaming producer strategy (requires a service that uses "stream" mode as input and output)
-
Java
-
XML
-
YAML
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}"); <route>
<from uri="direct:grpc-request-stream"/>
<to uri="grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong?method=PingAsyncAsync&producerStrategy=STREAMING&streamRepliesTo=direct:grpc-response-stream"/>
</route>
<route>
<from uri="direct:grpc-response-stream"/>
<log message="Response received: ${body}"/>
</route> - route:
from:
uri: direct:grpc-request-stream
steps:
- to:
uri: grpc://remotehost:1101/org.apache.camel.component.grpc.PingPong
parameters:
method: PingAsyncAsync
producerStrategy: STREAMING
streamRepliesTo: direct:grpc-response-stream
- route:
from:
uri: direct:grpc-response-stream
steps:
- log: "Response received: ${body}" gRPC service consumer TLS/SSL security negotiation enabled
-
Java
-
XML
-
YAML
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"); <route>
<from uri="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 uri="direct:tls-enable"/>
</route> - route:
from:
uri: grpc://localhost:1101/org.apache.camel.component.grpc.PingPong
parameters:
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"
steps:
- to:
uri: direct:tls-enable gRPC service producer with TLS, where only the server is authenticated. The server certificate is verified with trustCertCollectionResource, or with the default trust store of the JVM when that option is not set. Add keyCertChainResource and keyResource only when the server requires a client certificate (mutual TLS).
-
Java
-
XML
-
YAML
from("direct:grpc-tls")
.to("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?method=pingSyncSync&synchronous=true&negotiationType=TLS&trustCertCollectionResource=file:src/test/resources/certs/ca.pem"); <route>
<from uri="direct:grpc-tls"/>
<to uri="grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?method=pingSyncSync&synchronous=true&negotiationType=TLS&trustCertCollectionResource=file:src/test/resources/certs/ca.pem"/>
</route> - route:
from:
uri: direct:grpc-tls
steps:
- to:
uri: grpc://localhost:1101/org.apache.camel.component.grpc.PingPong
parameters:
method: pingSyncSync
synchronous: true
negotiationType: TLS
trustCertCollectionResource: "file:src/test/resources/certs/ca.pem" gRPC service producer with custom JSON Web Token (JWT) implementation authentication
-
Java
-
XML
-
YAML
from("direct:grpc-jwt")
.to("grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?method=pingSyncSync&synchronous=true&authenticationType=JWT&jwtSecret=supersecuredsecret"); <route>
<from uri="direct:grpc-jwt"/>
<to uri="grpc://localhost:1101/org.apache.camel.component.grpc.PingPong?method=pingSyncSync&synchronous=true&authenticationType=JWT&jwtSecret=supersecuredsecret"/>
</route> - route:
from:
uri: direct:grpc-jwt
steps:
- to:
uri: grpc://localhost:1101/org.apache.camel.component.grpc.PingPong
parameters:
method: pingSyncSync
synchronous: true
authenticationType: JWT
jwtSecret: supersecuredsecret Configuration
It is recommended to 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 procedure request and response classes, their builders and gRPC procedures stubs classes as well.
The 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 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>