Camel Components

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>

URI format

consul://domain?[options]

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, *.yaml files, 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

connectTimeout (common)

The connect timeout of the HTTP client. When not set, the default of the OkHttp client applies.

Duration

key (common)

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

pingInstance (common)

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

readTimeout (common)

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

tags (common)

Comma separated tags. The consul endpoints do not use this option, so setting it has no effect.

String

url (common)

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

valueAsString (common)

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

writeTimeout (common)

The write timeout of the HTTP client. When not set, the default of the OkHttp client applies.

Duration

bridgeErrorHandler (consumer)

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

action (producer)

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:

  • CHECKS

  • SERVICES

  • MEMBERS

  • AGENT

  • REGISTER

  • DEREGISTER

  • PUT

  • GET_VALUE

  • GET_VALUES

  • GET_KEYS

  • GET_SESSIONS

  • DELETE_KEY

  • DELETE_KEYS

  • LOCK

  • UNLOCK

  • LIST_DATACENTERS

  • LIST_NODES

  • LIST_SERVICES

  • GET_SERVICE

  • GET_NODE

  • NODE_CHECKS

  • SERVICE_CHECKS

  • SERVICE_INSTANCES

  • CREATE

  • DESTROY

  • INFO

  • LIST

  • RENEW

  • GET

  • EXECUTE

  • FIRE

  • DATACENTERS

  • NODES

  • LEADER

  • PEERS

String

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

configuration (advanced)

The shared configuration of the endpoints that this component creates. Each endpoint gets a copy, and the endpoint options override it.

ConsulConfiguration

consistencyMode (advanced)

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

  • STALE

  • CONSISTENT

DEFAULT

ConsistencyMode

consulClient (advanced)

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

datacenter (advanced)

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

nearNode (advanced)

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

nodeMeta (advanced)

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

aclToken (security)

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

password (security)

The password for HTTP basic authentication to the Consul agent. Used only together with userName.

String

sslContextParameters (security)

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

useGlobalSslContextParameters (security)

Whether to use the global SSL context parameters of the CamelContext for the endpoints that have no sslContextParameters.

false

boolean

userName (security)

The user name for HTTP basic authentication to the Consul agent. Used only together with password.

String

blockSeconds (watch)

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

firstIndex (watch)

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

recursive (watch)

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:

Path Parameters

Name Description Default Type

apiEndpoint (common)

Required The Consul API to use: kv, event, agent, catalog, health, session, preparedQuery, coordinates or status. Only kv and event have a consumer, the others only a producer; any other value is used as kv.

String

Query Parameters

Name Description Default Type

connectTimeout (common)

The connect timeout of the HTTP client. When not set, the default of the OkHttp client applies.

Duration

key (common)

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

pingInstance (common)

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

readTimeout (common)

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

tags (common)

Comma separated tags. The consul endpoints do not use this option, so setting it has no effect.

String

url (common)

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

valueAsString (common)

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

writeTimeout (common)

The write timeout of the HTTP client. When not set, the default of the OkHttp client applies.

Duration

bridgeErrorHandler (consumer (advanced))

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

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

action (producer)

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:

  • CHECKS

  • SERVICES

  • MEMBERS

  • AGENT

  • REGISTER

  • DEREGISTER

  • PUT

  • GET_VALUE

  • GET_VALUES

  • GET_KEYS

  • GET_SESSIONS

  • DELETE_KEY

  • DELETE_KEYS

  • LOCK

  • UNLOCK

  • LIST_DATACENTERS

  • LIST_NODES

  • LIST_SERVICES

  • GET_SERVICE

  • GET_NODE

  • NODE_CHECKS

  • SERVICE_CHECKS

  • SERVICE_INSTANCES

  • CREATE

  • DESTROY

  • INFO

  • LIST

  • RENEW

  • GET

  • EXECUTE

  • FIRE

  • DATACENTERS

  • NODES

  • LEADER

  • PEERS

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

consistencyMode (advanced)

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

  • STALE

  • CONSISTENT

DEFAULT

ConsistencyMode

consulClient (advanced)

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

datacenter (advanced)

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

nearNode (advanced)

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

nodeMeta (advanced)

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

aclToken (security)

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

password (security)

The password for HTTP basic authentication to the Consul agent. Used only together with userName.

String

sslContextParameters (security)

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

userName (security)

The user name for HTTP basic authentication to the Consul agent. Used only together with password.

String

blockSeconds (watch)

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

firstIndex (watch)

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

recursive (watch)

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

CamelConsulAction (producer)

Constant: CONSUL_ACTION

The action to run, overriding the action option.

String

CamelConsulKey (common)

Constant: CONSUL_KEY

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

CamelConsulEventId (consumer)

Constant: CONSUL_EVENT_ID

The id of the received event.

String

CamelConsulEventName (consumer)

Constant: CONSUL_EVENT_NAME

The name of the received event.

String

CamelConsulEventLTime (consumer)

Constant: CONSUL_EVENT_LTIME

The Lamport time of the received event.

Long

CamelConsulNodeFilter (consumer)

Constant: CONSUL_NODE_FILTER

The node name filter (a regular expression) of the received event, when it has one.

String

CamelConsulTagFilter (consumer)

Constant: CONSUL_TAG_FILTER

The service tag filter (a regular expression) of the received event, when it has one.

String

CamelConsulSessionFilter (consumer)

Constant: CONSUL_SERVICE_FILTER

The service name filter (a regular expression) of the received event, when it has one.

String

CamelConsulVersion (consumer)

Constant: CONSUL_VERSION

The version of the received event.

Integer

CamelConsulFlags (common)

Constant: CONSUL_FLAGS

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

CamelConsulIndex (producer)

Constant: CONSUL_INDEX

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

CamelConsulWait (producer)

Constant: CONSUL_WAIT

The maximum wait time of a blocking catalog or health query, such as 10s or 5m.

String

CamelConsulCreateIndex (consumer)

Constant: CONSUL_CREATE_INDEX

The index at which the key was created.

Long

CamelConsulLockIndex (consumer)

Constant: CONSUL_LOCK_INDEX

The number of times that a lock on the key was acquired.

Long

CamelConsulModifyIndex (consumer)

Constant: CONSUL_MODIFY_INDEX

The index at which the key was last modified.

Long

CamelConsulOptions (common)

Constant: CONSUL_OPTIONS

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.

CamelConsulResult (common)

Constant: CONSUL_RESULT

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

CamelConsulSession (common)

Constant: CONSUL_SESSION

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: CONSUL_VALUE_AS_STRING

Whether GET_VALUE and GET_VALUES return the values decoded to text, overriding the valueAsString option.

Boolean

CamelConsulNode (producer)

Constant: CONSUL_NODE

The node name for the GET_NODE action of catalog and the NODE_CHECKS action of health.

String

CamelConsulService (producer)

Constant: CONSUL_SERVICE

The service name for the GET_SERVICE action of catalog and the SERVICE_CHECKS and SERVICE_INSTANCES actions of health.

String

CamelConsulDatacenter (producer)

Constant: CONSUL_DATACENTER

The datacenter to query, overriding the datacenter option. The session actions use only this header.

String

CamelConsulNearNode (producer)

Constant: CONSUL_NEAR_NODE

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: CONSUL_NODE_META

The node metadata filters, each as key:value, of the catalog and health queries, overriding the nodeMeta option.

List

CamelConsulLastContact (producer)

Constant: CONSUL_LAST_CONTACT

The time in milliseconds since the server that answered a catalog or health query last had contact with the leader.

Long

CamelConsulKnownLeader (producer)

Constant: CONSUL_KNOWN_LEADER

Whether the server that answered a catalog or health query knew the leader.

Boolean

CamelConsulConsistencyMode (producer)

Constant: CONSUL_CONSISTENCY_MODE

The consistency mode of the catalog and health queries, overriding the consistencyMode option.

DEFAULT

ConsistencyMode

CamelConsulHealthyOnly (producer)

Constant: CONSUL_HEALTHY_ONLY

Whether the SERVICE_INSTANCES action returns only the instances that pass all their health checks.

false

Boolean

CamelConsulHealthyState (producer)

Constant: CONSUL_HEALTHY_STATE

The state of the health checks that the CHECKS action of health returns. Required for that action.

Enum values:

  • PASS

  • WARN

  • FAIL

  • ANY

  • UNKNOWN

State

CamelConsulPreparedQueryID (producer)

Constant: CONSUL_PREPARED_QUERY_ID

The id of the prepared query for GET and EXECUTE. When not set, the body holds the id.

String

CamelConsulServiceId (producer)

Constant: CONSUL_SERVICE_ID

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

text or null

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

any

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.

  • With action=PUT: text, bytes, stream, file, value or null

  • With action=LOCK: text, bytes, stream, file, value or null

  • With action=FIRE: text, bytes, stream, file, value or null

  • With action=REGISTER: pojo

  • With action=CREATE: pojo

Producer output

pojo, list, map, text or unchanged

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.

  • With action=CHECKS: map or list

  • With action=SERVICES: map

  • With action=MEMBERS: list

  • With action=AGENT: pojo (org.kiwiproject.consul.model.agent.Agent)

  • With action=REGISTER: unchanged

  • With action=DEREGISTER: unchanged

  • With action=PUT: unchanged

  • With action=GET_VALUE: pojo, text or unchanged

  • With action=GET_VALUES: list

  • With action=GET_KEYS: list

  • With action=GET_SESSIONS: text or unchanged (java.lang.String)

  • With action=DELETE_KEY: unchanged

  • With action=DELETE_KEYS: unchanged

  • With action=LOCK: unchanged

  • With action=UNLOCK: unchanged

  • With action=LIST_DATACENTERS: list

  • With action=LIST_NODES: list

  • With action=LIST_SERVICES: map

  • With action=GET_SERVICE: list

  • With action=GET_NODE: pojo (org.kiwiproject.consul.model.catalog.CatalogNode)

  • With action=NODE_CHECKS: list

  • With action=SERVICE_CHECKS: list

  • With action=SERVICE_INSTANCES: list

  • With action=CREATE: pojo or text

  • With action=DESTROY: unchanged

  • With action=INFO: pojo or unchanged

  • With action=LIST: pojo or list

  • With action=RENEW: pojo or unchanged (org.kiwiproject.consul.model.session.SessionInfo)

  • With action=GET: pojo or unchanged (org.kiwiproject.consul.model.query.StoredQuery)

  • With action=EXECUTE: pojo (org.kiwiproject.consul.model.query.QueryResults)

  • With action=FIRE: pojo (org.kiwiproject.consul.model.event.Event)

  • With action=DATACENTERS: list

  • With action=NODES: list

  • With action=LEADER: text (java.lang.String)

  • With action=PEERS: list

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 ConsulAgentProducer maps ConsulAgentActions.REGISTER to an invocation of AgentClient.register.

Java-only: route using ImmutableRegistration builder and Java constants
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.

Java-only: route with programmatic routePolicy and Java constants
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())
...