Consul
Since Camel 2.18
Both producer and consumer are supported
The Consul component is a component for integrating your application with Hashicorp Consul.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-consul</artifactId>
<version>${camel-version}</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 Consul component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
The connect timeout of the HTTP client. When not set, the default of the OkHttp client applies. | Duration | ||
The key (kv) or event name (event) that the consumer watches or that the producer acts on; the other APIs do not use it. In a producer, a CamelConsulKey header overrides it, unless the header still holds the key that a consul consumer received (the CamelConsulReceivedKey exchange property). | String | ||
Whether the Consul client pings the agent when it is created, so that creating it fails when the agent cannot be reached. The client is created when the consumer starts or when the producer handles its first message. | true | boolean | |
The read timeout of the HTTP client. When not set, the default of the OkHttp client applies; the Consul client extends it for the blocking queries of the consumers. | Duration | ||
Comma separated tags. The consul endpoints do not use this option, so setting it has no effect. | String | ||
The URL of the Consul agent that the client connects to, such as http://localhost:8500 (the default of the Consul client when not set). Use an https URL to connect with sslContextParameters. | String | ||
Whether the values of the kv API are decoded to text: the kv consumer then sets the decoded value as the body instead of the base64 encoded value, and the GET_VALUE and GET_VALUES actions return a String (a List of them) instead of Value objects. In a producer, the CamelConsulValueAsString header overrides it. | false | boolean | |
The write timeout of the HTTP client. When not set, the default of the OkHttp client applies. | Duration | ||
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 | |
The default action. Can be overridden by CamelConsulAction. The actions depend on the API of the endpoint: agent has CHECKS, SERVICES, MEMBERS, AGENT, REGISTER and DEREGISTER; kv has PUT, GET_VALUE, GET_VALUES, GET_KEYS, GET_SESSIONS, DELETE_KEY, DELETE_KEYS, LOCK and UNLOCK; catalog has REGISTER, DEREGISTER, LIST_DATACENTERS, LIST_NODES, LIST_SERVICES, GET_SERVICE and GET_NODE; health has CHECKS, NODE_CHECKS, SERVICE_CHECKS and SERVICE_INSTANCES; session has CREATE, DESTROY, INFO, LIST and RENEW; preparedQuery has CREATE, GET and EXECUTE; event has FIRE and LIST; coordinates has DATACENTERS and NODES; status has LEADER and PEERS. Enum values:
| 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 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 shared configuration of the endpoints that this component creates. Each endpoint gets a copy, and the endpoint options override it. | ConsulConfiguration | ||
The consistency mode of the catalog and health queries: DEFAULT (the leader answers), STALE (any server answers, possibly with outdated data) or CONSISTENT (the leader first checks with a quorum that it is still the leader). The CamelConsulConsistencyMode header overrides it. Enum values:
| DEFAULT | ConsistencyMode | |
Autowired The Consul client (org.kiwiproject.consul.Consul) to use instead of creating one. When set, the options that create the client (url, sslContextParameters, aclToken, userName, password, the timeouts and pingInstance) are not used. | Consul | ||
The datacenter to query instead of the datacenter of the agent. Used by the catalog and health queries, the agent DEREGISTER action and the coordinates NODES action; the CamelConsulDatacenter header overrides it. | String | ||
The name of a node (or _agent for the node of the agent) from which Consul sorts the results of the catalog and health queries by estimated round trip time. The CamelConsulNearNode header overrides it. | String | ||
Comma separated node metadata filters, each as key:value, so that the catalog and health queries return only the nodes with that metadata. The CamelConsulNodeMeta header overrides it. | String | ||
The ACL token that the client sends with each request to Consul, in the X-Consul-Token header. Not used when a consulClient is set: configure the token on that client instead. | String | ||
The password for HTTP basic authentication to the Consul agent. Used only together with userName. | String | ||
The SSL configuration of the HTTPS connection to the Consul agent. When not set, the global SSL context parameters are used if the component enables useGlobalSslContextParameters. | SSLContextParameters | ||
Whether to use the global SSL context parameters of the CamelContext for the endpoints that have no sslContextParameters. | false | boolean | |
The user name for HTTP basic authentication to the Consul agent. Used only together with password. | String | ||
The wait time in seconds of the blocking query with which the kv and event consumers watch: Consul answers when the data changes or when the time is up, and the consumer then queries again. The event consumer also waits this long before each query, and both wait this long (at least one second) before they query again after an error. | 10 | Integer | |
The Consul index from which the first blocking query of the kv or event consumer waits for a change. With 0 the first query answers at once, so the consumer receives the current value of the key, or the events that Consul still keeps. | 0 | BigInteger | |
Whether the kv consumer watches all the keys under the key (as a prefix) instead of only the key. When one of them changes, the consumer receives a message for each key under the prefix. | false | boolean |
Endpoint Options
The Consul endpoint is configured using URI syntax:
consul:apiEndpoint
With the following path and query parameters:
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The connect timeout of the HTTP client. When not set, the default of the OkHttp client applies. | Duration | ||
The key (kv) or event name (event) that the consumer watches or that the producer acts on; the other APIs do not use it. In a producer, a CamelConsulKey header overrides it, unless the header still holds the key that a consul consumer received (the CamelConsulReceivedKey exchange property). | String | ||
Whether the Consul client pings the agent when it is created, so that creating it fails when the agent cannot be reached. The client is created when the consumer starts or when the producer handles its first message. | true | boolean | |
The read timeout of the HTTP client. When not set, the default of the OkHttp client applies; the Consul client extends it for the blocking queries of the consumers. | Duration | ||
Comma separated tags. The consul endpoints do not use this option, so setting it has no effect. | String | ||
The URL of the Consul agent that the client connects to, such as http://localhost:8500 (the default of the Consul client when not set). Use an https URL to connect with sslContextParameters. | String | ||
Whether the values of the kv API are decoded to text: the kv consumer then sets the decoded value as the body instead of the base64 encoded value, and the GET_VALUE and GET_VALUES actions return a String (a List of them) instead of Value objects. In a producer, the CamelConsulValueAsString header overrides it. | false | boolean | |
The write timeout of the HTTP client. When not set, the default of the OkHttp client applies. | Duration | ||
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 | ||
The default action. Can be overridden by CamelConsulAction. The actions depend on the API of the endpoint: agent has CHECKS, SERVICES, MEMBERS, AGENT, REGISTER and DEREGISTER; kv has PUT, GET_VALUE, GET_VALUES, GET_KEYS, GET_SESSIONS, DELETE_KEY, DELETE_KEYS, LOCK and UNLOCK; catalog has REGISTER, DEREGISTER, LIST_DATACENTERS, LIST_NODES, LIST_SERVICES, GET_SERVICE and GET_NODE; health has CHECKS, NODE_CHECKS, SERVICE_CHECKS and SERVICE_INSTANCES; session has CREATE, DESTROY, INFO, LIST and RENEW; preparedQuery has CREATE, GET and EXECUTE; event has FIRE and LIST; coordinates has DATACENTERS and NODES; status has LEADER and PEERS. Enum values:
| 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 | |
The consistency mode of the catalog and health queries: DEFAULT (the leader answers), STALE (any server answers, possibly with outdated data) or CONSISTENT (the leader first checks with a quorum that it is still the leader). The CamelConsulConsistencyMode header overrides it. Enum values:
| DEFAULT | ConsistencyMode | |
Autowired The Consul client (org.kiwiproject.consul.Consul) to use instead of creating one. When set, the options that create the client (url, sslContextParameters, aclToken, userName, password, the timeouts and pingInstance) are not used. | Consul | ||
The datacenter to query instead of the datacenter of the agent. Used by the catalog and health queries, the agent DEREGISTER action and the coordinates NODES action; the CamelConsulDatacenter header overrides it. | String | ||
The name of a node (or _agent for the node of the agent) from which Consul sorts the results of the catalog and health queries by estimated round trip time. The CamelConsulNearNode header overrides it. | String | ||
Comma separated node metadata filters, each as key:value, so that the catalog and health queries return only the nodes with that metadata. The CamelConsulNodeMeta header overrides it. | String | ||
The ACL token that the client sends with each request to Consul, in the X-Consul-Token header. Not used when a consulClient is set: configure the token on that client instead. | String | ||
The password for HTTP basic authentication to the Consul agent. Used only together with userName. | String | ||
The SSL configuration of the HTTPS connection to the Consul agent. When not set, the global SSL context parameters are used if the component enables useGlobalSslContextParameters. | SSLContextParameters | ||
The user name for HTTP basic authentication to the Consul agent. Used only together with password. | String | ||
The wait time in seconds of the blocking query with which the kv and event consumers watch: Consul answers when the data changes or when the time is up, and the consumer then queries again. The event consumer also waits this long before each query, and both wait this long (at least one second) before they query again after an error. | 10 | Integer | |
The Consul index from which the first blocking query of the kv or event consumer waits for a change. With 0 the first query answers at once, so the consumer receives the current value of the key, or the events that Consul still keeps. | 0 | BigInteger | |
Whether the kv consumer watches all the keys under the key (as a prefix) instead of only the key. When one of them changes, the consumer receives a message for each key under the prefix. | false | boolean |
Message Headers
The Consul component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The action to run, overriding the action option. | String | |
| Constant: | The consumer sets the key of the value (kv) or the event name (event). In a producer, the key (kv) or event name (event) to act on, overriding the key option. | String | |
| Constant: | The id of the received event. | String | |
CamelConsulEventName (consumer) Constant: | The name of the received event. | String | |
CamelConsulEventLTime (consumer) Constant: | The Lamport time of the received event. | Long | |
CamelConsulNodeFilter (consumer) Constant: | The node name filter (a regular expression) of the received event, when it has one. | String | |
CamelConsulTagFilter (consumer) Constant: | The service tag filter (a regular expression) of the received event, when it has one. | String | |
CamelConsulSessionFilter (consumer) Constant: | The service name filter (a regular expression) of the received event, when it has one. | String | |
| Constant: | The version of the received event. | Integer | |
| Constant: | The flags of the value. The kv consumer sets the flags of the value it received, and the PUT action stores them with the value (default 0). | Long | |
| Constant: | The index from which a blocking catalog or health query waits for a change. These actions set it to the index of the answer. | BigInteger | |
| Constant: | The maximum wait time of a blocking catalog or health query, such as 10s or 5m. | String | |
CamelConsulCreateIndex (consumer) Constant: | The index at which the key was created. | Long | |
CamelConsulLockIndex (consumer) Constant: | The number of times that a lock on the key was acquired. | Long | |
CamelConsulModifyIndex (consumer) Constant: | The index at which the key was last modified. | Long | |
| Constant: | The options of the request, as an object of org.kiwiproject.consul.option: PutOptions for PUT, QueryOptions for GET_VALUE, GET_VALUES and the event LIST, and EventOptions for FIRE. | ||
| Constant: | Whether the action had a result: false when nothing was found, else the outcome of PUT, LOCK and UNLOCK, and true for the other actions. The consumers set it to true. | Boolean | |
| Constant: | The id of the session. The kv consumer sets the session that holds the lock on the key. LOCK and UNLOCK use it, and DESTROY, INFO and RENEW of session read it before the body. | String | |
CamelConsulValueAsString (producer) Constant: | Whether GET_VALUE and GET_VALUES return the values decoded to text, overriding the valueAsString option. | Boolean | |
| Constant: | The node name for the GET_NODE action of catalog and the NODE_CHECKS action of health. | String | |
| Constant: | The service name for the GET_SERVICE action of catalog and the SERVICE_CHECKS and SERVICE_INSTANCES actions of health. | String | |
CamelConsulDatacenter (producer) Constant: | The datacenter to query, overriding the datacenter option. The session actions use only this header. | String | |
CamelConsulNearNode (producer) Constant: | The node from which Consul sorts the results of the catalog and health queries by round trip time, overriding the nearNode option. | String | |
CamelConsulNodeMeta (producer) Constant: | The node metadata filters, each as key:value, of the catalog and health queries, overriding the nodeMeta option. | List | |
CamelConsulLastContact (producer) Constant: | The time in milliseconds since the server that answered a catalog or health query last had contact with the leader. | Long | |
CamelConsulKnownLeader (producer) Constant: | Whether the server that answered a catalog or health query knew the leader. | Boolean | |
CamelConsulConsistencyMode (producer) Constant: | The consistency mode of the catalog and health queries, overriding the consistencyMode option. | DEFAULT | ConsistencyMode |
CamelConsulHealthyOnly (producer) Constant: | Whether the SERVICE_INSTANCES action returns only the instances that pass all their health checks. | false | Boolean |
CamelConsulHealthyState (producer) Constant: | The state of the health checks that the CHECKS action of health returns. Required for that action. Enum values:
| State | |
CamelConsulPreparedQueryID (producer) Constant: | The id of the prepared query for GET and EXECUTE. When not set, the body holds the id. | String | |
CamelConsulServiceId (producer) Constant: | The id of the service that the DEREGISTER action of agent removes. Required for that action. | String |
Message Body
The message body at each side of the Consul 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 kv consumer: the value of the key (of each key under it with recursive) base64 encoded as Consul stores it, decoded with valueAsString=true, with the key, flags and indexes in headers; null for a key without value. The event consumer: the payload of the event as text, with its name and id in headers. |
Producer input |
| PUT and LOCK store the body converted to text as the value, and FIRE sends it as the payload (an event without payload for a null body): a Map or a POJO is stored as its toString, so marshal it first. REGISTER, DEREGISTER of catalog and CREATE take the model object of the Consul client, such as a Registration or a Session; the session and prepared query actions read the id from the body when its header is not set; the other actions take their input from headers.
|
Producer output |
| The response of Consul as the model objects of the Consul client: a List or a Map of them for the list actions, the Value of the key for GET_VALUE (its value base64 encoded) or the value as text with valueAsString=true, and the Event for FIRE. Unchanged for the actions that only write (PUT, the deletes, LOCK, UNLOCK, REGISTER, DEREGISTER, DESTROY) and when nothing is found, with the outcome in the CamelConsulResult header.
|
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
Api Endpoint
The apiEndpoint denotes the type of consul api which should be addressed.
| Domain | Producer | Consumer |
|---|---|---|
kv | ConsulKeyValueProducer | ConsulKeyValueConsumer |
event | ConsulEventProducer | ConsulEventConsumer |
agent | ConsulAgentProducer | - |
coordinates | ConsulCoordinatesProducer | - |
health | ConsulHealthProducer | - |
status | ConsulStatusProducer | - |
preparedQuery | ConsulPreparedQueryProducer | - |
catalog | ConsulCatalogProducer | - |
session | ConsulSessionProducer | - |
ACL token
The client that the endpoint creates sends the aclToken in the X-Consul-Token header of each request, never in the URL.
When you set your own consulClient, the aclToken option is not used: configure the token on that client, for example with Consul.builder().withTokenAuth(token). The withAclToken(token) method of the Consul client adds the token to the URL of each request as the token query parameter.
Examples
Producer Examples
As an example, we will show how to use the ConsulAgentProducer to register a service by means of the Consul agent api.
Registering and unregistering are examples for possible actions against the Consul agent api.
The desired action can be defined by setting the header CamelConsulAction to a value from the respective Consul api.
If you set CONSUL_ACTION to ConsulAgentActions.REGISTER, the agent action REGISTER will be executed.
| Which producer action invoked by which consul api is defined by the respective producer. E.g., the |
from("direct:registerFooService")
.setBody().constant(ImmutableRegistration.builder()
.id("foo-1")
.name("foo")
.address("localhost")
.port(80)
.build())
.setHeader("CamelConsulAction", constant("REGISTER"))
.to("consul:agent"); It is also possible to set a default action on the consul endpoint and do without the header:
consul:agent?action=REGISTER
Key-value store
The kv endpoint reads and writes the key-value store of Consul. The action comes from the action option or the CamelConsulAction header (the header wins), and the key from the key option or the CamelConsulKey header. A PUT stores the message body, converted to a string, as the value. A GET_VALUE sets the Value of the Consul client as the message body, which holds the value base64 encoded, and valueAsString makes the body the value as a string:
- route:
from:
uri: direct:save-greeting
steps:
- setHeader:
name: CamelConsulAction
expression:
constant:
expression: PUT
- to:
uri: consul:kv
parameters:
key: app/greeting
- route:
from:
uri: direct:read-greeting
steps:
- setHeader:
name: CamelConsulAction
expression:
constant:
expression: GET_VALUE
- to:
uri: consul:kv
parameters:
key: app/greeting
valueAsString: true
- log:
message: "The greeting is ${body}" A consumer of the kv endpoint watches a key with a blocking query of blockSeconds (10 by default). The route gets the value each time the query returns: when the value changes, or when the wait ends. The body is the value base64 encoded, as Consul stores it, unless valueAsString is set.
- route:
from:
uri: consul:kv
parameters:
key: app/greeting
valueAsString: true
steps:
- log:
message: "${header.CamelConsulKey} is now ${body}" The kv and event consumers set the CamelConsulKey header to the key (or event name) they received. While the header still holds that key, a producer that has a key of its own uses its key, so a route from one key to another (from("consul:kv?key=a").to("consul:kv?key=b&action=PUT")) writes b, not a. A key header set by the route is used, and a producer without key acts on the received key, for example to delete each key of a recursive watch once it is processed. To act on the received key with a producer that has a key, remove the CamelConsulReceivedKey exchange property (which the consumers set to the received key) before the producer, such as with .removeProperty(ConsulConstants.CONSUL_RECEIVED_KEY).
The client connects to the Consul agent at http://localhost:8500, unless you set the url option, for example with camel.component.consul.url in application.properties.
Registering Camel Routes with Consul
You can employ a ServiceRegistrationRoutePolicy to register Camel routes as services with Consul automatically.
from("jetty:http://0.0.0.0:8080/service/endpoint").routeId("foo-1")
.routeProperty(ServiceDefinition.SERVICE_META_ID, "foo-1")
.routeProperty(ServiceDefinition.SERVICE_META_NAME, "foo")
.routePolicy(new ServiceRegistrationRoutePolicy())
...