ZooKeeper
Since Camel 2.9
Both producer and consumer are supported
The ZooKeeper component allows interaction with a ZooKeeper cluster and exposes the following features to Camel:
-
Creation of nodes in any of the ZooKeeper create modes.
-
Get and Set the data contents of arbitrary cluster nodes (data being set must be convertible to
byte[]). -
Create and retrieve the list of the child nodes attached to a particular node.
Maven users will need to add the following dependency to their pom.xml for this component:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-zookeeper</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel core version -->
</dependency> URI format
zookeeper://zookeeper-server[:port][/path][?options]
The path from the URI specifies the node in the ZooKeeper server (a.k.a. znode) that will be the target of the endpoint:
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 ZooKeeper component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
Whether to use the names of the child znodes (a List of String) instead of the data. The consumer sends the child names of the znode, and with repeat again each time a child is created or deleted. The producer, for an InOut exchange, sets the body to the child names of the endpoint path after the write or delete. | false | boolean | |
The ZooKeeper session timeout in milliseconds that the client asks for: when the servers hear nothing from the client for this long, the session expires and its ephemeral znodes are deleted. The server keeps the value within its bounds, by default 2 to 20 times its tickTime. The client also derives its connect timeout per server (this value divided by the number of servers) and its read timeout (two thirds of this value) from it. Camel waits without a time limit for the client to connect. | 5000 | int | |
The delay in milliseconds after the consumer failed to read or watch the znode (for example because the session expired) before it starts again: it opens a new session when the previous one can no longer be used, and reads the znode again. | 5000 | long | |
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 consumer keeps watching the znode: it sends the data (or the child list) again each time it changes, and after a delete it waits for the znode to be created again. Without it, the consumer sends the data (or the child list) once, waiting for the znode to be created if it does not exist yet; only a delete of the znode before its next change still sends a message (see sendEmptyMessageOnDelete). | false | boolean | |
Whether the consumer sends a message without a body when the znode is deleted, with the CamelZookeeperEventType header set to NodeDeleted. Does not apply with listChildren. | true | boolean | |
Whether the producer creates the znode when a write finds that it does not exist. The new znode gets the body as data, the create mode of the createMode option (or of the CamelZookeeperCreateMode header) and the ACL of the CamelZookeeperAcl header (by default OPEN_ACL_UNSAFE, which gives anyone all permissions). Missing parent znodes are created as PERSISTENT znodes with OPEN_ACL_UNSAFE. A DELETE never creates a znode. | false | boolean | |
The create mode of a znode that the producer creates (see create). An EPHEMERAL znode is deleted when the session of the endpoint ends, such as when the route stops; with a SEQUENTIAL mode ZooKeeper appends a sequence number to the name, and each write creates a new znode. When this option is not set, the CamelZookeeperCreateMode header decides, and EPHEMERAL is used when there is no header either. Enum values:
| EPHEMERAL | 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 | |
A shared ZooKeeperConfiguration with the default options of the endpoints; each endpoint uses a copy of it. | ZooKeeperConfiguration |
Endpoint Options
The ZooKeeper endpoint is configured using URI syntax:
zookeeper:serverUrls/path
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Required The ZooKeeper servers to connect to, as a comma-separated list of host:port, such as zk1:2181,zk2:2181. The ZooKeeper client uses port 2181 for a host without a port. | String | ||
Required The absolute path of the znode, such as /camel/config. The consumer reads and watches this znode; the producer writes or deletes it, unless the CamelZooKeeperNode header names another path. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
Whether to use the names of the child znodes (a List of String) instead of the data. The consumer sends the child names of the znode, and with repeat again each time a child is created or deleted. The producer, for an InOut exchange, sets the body to the child names of the endpoint path after the write or delete. | false | boolean | |
The ZooKeeper session timeout in milliseconds that the client asks for: when the servers hear nothing from the client for this long, the session expires and its ephemeral znodes are deleted. The server keeps the value within its bounds, by default 2 to 20 times its tickTime. The client also derives its connect timeout per server (this value divided by the number of servers) and its read timeout (two thirds of this value) from it. Camel waits without a time limit for the client to connect. | 5000 | int | |
The delay in milliseconds after the consumer failed to read or watch the znode (for example because the session expired) before it starts again: it opens a new session when the previous one can no longer be used, and reads the znode again. | 5000 | long | |
Whether the consumer keeps watching the znode: it sends the data (or the child list) again each time it changes, and after a delete it waits for the znode to be created again. Without it, the consumer sends the data (or the child list) once, waiting for the znode to be created if it does not exist yet; only a delete of the znode before its next change still sends a message (see sendEmptyMessageOnDelete). | false | boolean | |
Whether the consumer sends a message without a body when the znode is deleted, with the CamelZookeeperEventType header set to NodeDeleted. Does not apply with listChildren. | true | 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 creates the znode when a write finds that it does not exist. The new znode gets the body as data, the create mode of the createMode option (or of the CamelZookeeperCreateMode header) and the ACL of the CamelZookeeperAcl header (by default OPEN_ACL_UNSAFE, which gives anyone all permissions). Missing parent znodes are created as PERSISTENT znodes with OPEN_ACL_UNSAFE. A DELETE never creates a znode. | false | boolean | |
The create mode of a znode that the producer creates (see create). An EPHEMERAL znode is deleted when the session of the endpoint ends, such as when the route stops; with a SEQUENTIAL mode ZooKeeper appends a sequence number to the name, and each write creates a new znode. When this option is not set, the CamelZookeeperCreateMode header decides, and EPHEMERAL is used when there is no header either. Enum values:
| EPHEMERAL | 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 |
Message Headers
The ZooKeeper component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The path of the znode. The producer writes or deletes the znode of this path instead of the path of the endpoint. The consumer sets it to the path of the znode that the message comes from. | String | |
CamelZooKeeperVersion (common) Constant: | The version that the znode must have for the producer to write or delete it; with another version the exchange fails with a BadVersionException. -1 matches any version. The consumer gives the version in the CamelZookeeperStatistics header instead. | -1 | Integer |
| Constant: | The ACL of a znode that the producer creates (see the create option). The default Ids.OPEN_ACL_UNSAFE gives anyone all permissions on the znode. Not used when the znode already exists, nor for the parent znodes that are created, which always get OPEN_ACL_UNSAFE. | Ids.OPEN_ACL_UNSAFE | List |
CamelZookeeperCreateMode (common) Constant: | The create mode of a znode that the producer creates (see the create option), as a CreateMode or its name, such as PERSISTENT. Only used when the createMode option is not set; an unknown name, or no header, means EPHEMERAL. | CreateMode or String | |
CamelZookeeperStatistics (common) Constant: | The Stat of the znode that ZooKeeper returned for the read or write, with the metadata of the znode such as its version, data length, number of children and modification time. The consumer sets it for each message, and the producer for an InOut exchange. It is empty for a znode that the producer created, and not set after a delete. | Stat | |
CamelZookeeperEventType (common) Constant: | The type of the ZooKeeper watch event that made the consumer send this message, such as NodeCreated, NodeDataChanged, NodeChildrenChanged or NodeDeleted. Not set when the consumer reads a znode that already existed when it started. Enum values:
| EventType | |
CamelZookeeperOperation (producer) Constant: | The operation of the producer: DELETE deletes the znode, which fails with a NotEmptyException when it has child znodes. Any other value, or no header, writes the body as the data of the znode. | String |
Message Body
The message body at each side of the ZooKeeper 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 data of the znode as bytes, and no body when the znode is deleted; with listChildren, the List of the names of its child znodes. The CamelZooKeeperNode and CamelZookeeperStatistics headers say which znode and its version.
Not known when |
Producer input |
| The data to store in the znode, converted to bytes; a null body stores no data. A Map, a POJO or a number is not converted and fails the exchange; with the CamelZookeeperOperation header set to DELETE the body is not read. |
Producer output |
| Both wait for the write or delete, and fail the exchange when it failed. InOnly leaves the body unchanged. InOut sets the bytes written, the path of the znode as text when it was created, or true for a DELETE; with listChildren, the List of the names of the child znodes of the path.
|
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
Reading from a znode
The following snippet will read the data from the znode /somepath/somenode/ provided that it already exists. The data retrieved will be placed into an exchange and passed onto the rest of the route:
-
Java
-
XML
-
YAML
from("zookeeper://localhost:39913/somepath/somenode").to("mock:result"); <route>
<from uri="zookeeper://localhost:39913/somepath/somenode"/>
<to uri="mock:result"/>
</route> - route:
from:
uri: zookeeper://localhost:39913/somepath/somenode
steps:
- to:
uri: mock:result If the node does not exist yet, the consumer waits for it to be created before reading it.
The consumer reads the data of the node (or its list of children with listChildren=true) once, and does not follow later changes. To receive each change as well, set repeat=true, for example zookeeper://localhost:39913/somepath/somenode?repeat=true.
Reading from a znode
When data is read due to a WatchedEvent received from the ZooKeeper ensemble, the CamelZookeeperEventType header holds ZooKeeper’s EventType value from that WatchedEvent. If the data is read initially (not triggered by a WatchedEvent) the CamelZookeeperEventType header will not be set.
Writing to a znode
The following snippet will write the payload of the exchange into the znode at /somepath/somenode/ provided that it already exists:
-
Java
-
XML
-
YAML
from("direct:write-to-znode")
.to("zookeeper://localhost:39913/somepath/somenode"); <route>
<from uri="direct:write-to-znode"/>
<to uri="zookeeper://localhost:39913/somepath/somenode"/>
</route> - route:
from:
uri: direct:write-to-znode
steps:
- to:
uri: zookeeper://localhost:39913/somepath/somenode For flexibility, the endpoint allows the target znode to be specified dynamically as a message header. If a header keyed by the string CamelZooKeeperNode is present then the value of the header will be used as the path to the znode on the server. For instance using the same route definition above, the following code snippet will write the data not to /somepath/somenode but to the path from the header /somepath/someothernode.
the testPayload must be convertible to byte[] as the data stored in ZooKeeper is byte-based. A body that cannot be converted, such as a Map, a POJO or a number, fails the exchange with an InvalidPayloadException. A null body stores no data in the znode. |
Object testPayload = ...
template.sendBodyAndHeader("direct:write-to-znode", testPayload, "CamelZooKeeperNode", "/somepath/someothernode"); To also create the node if it does not exist the create option should be used.
-
Java
-
XML
-
YAML
from("direct:create-and-write-to-znode")
.to("zookeeper://localhost:39913/somepath/somenode?create=true"); <route>
<from uri="direct:create-and-write-to-znode"/>
<to uri="zookeeper://localhost:39913/somepath/somenode?create=true"/>
</route> - route:
from:
uri: direct:create-and-write-to-znode
steps:
- to:
uri: zookeeper://localhost:39913/somepath/somenode
parameters:
create: true The producer waits for ZooKeeper to confirm the write, for an InOnly exchange too, and a failed write fails the exchange: for example a znode that does not exist without the create option, or a CamelZooKeeperVersion header that is not the current version of the znode. An InOnly exchange keeps its body; an InOut exchange gets the result of the write as its body.
It is also possible to delete a node using the header CamelZookeeperOperation by setting it to DELETE. A delete of a znode that does not exist fails the exchange with a NoNodeException; the create option does not apply to a delete:
-
Java
-
XML
-
YAML
from("direct:delete-znode")
.setHeader(ZooKeeperMessage.ZOOKEEPER_OPERATION, constant("DELETE"))
.to("zookeeper://localhost:39913/somepath/somenode"); <route>
<from uri="direct:delete-znode"/>
<setHeader name="CamelZookeeperOperation">
<constant>DELETE</constant>
</setHeader>
<to uri="zookeeper://localhost:39913/somepath/somenode"/>
</route> - route:
from:
uri: direct:delete-znode
steps:
- setHeader:
name: CamelZookeeperOperation
constant: DELETE
- to:
uri: zookeeper://localhost:39913/somepath/somenode ZooKeeper’s nodes can have different types; they can be 'Ephemeral' or 'Persistent' and 'Sequenced' or 'Unsequenced'. For further information of each type, you can check here. By default, endpoints will create unsequenced, ephemeral nodes, but the type can be easily manipulated via an URI config parameter or via a special message header. The values expected for the create mode are simply the names from the CreateMode enumeration:
-
PERSISTENT -
PERSISTENT_SEQUENTIAL -
EPHEMERAL -
EPHEMERAL_SEQUENTIAL
For example, to create a persistent znode via the URI config:
-
Java
-
XML
-
YAML
from("direct:create-and-write-to-persistent-znode")
.to("zookeeper://localhost:39913/somepath/somenode?create=true&createMode=PERSISTENT"); <route>
<from uri="direct:create-and-write-to-persistent-znode"/>
<to uri="zookeeper://localhost:39913/somepath/somenode?create=true&createMode=PERSISTENT"/>
</route> - route:
from:
uri: direct:create-and-write-to-persistent-znode
steps:
- to:
uri: zookeeper://localhost:39913/somepath/somenode
parameters:
create: true
createMode: PERSISTENT or using the header CamelZookeeperCreateMode.
the testPayload must be convertible to byte[] as the data stored in ZooKeeper is byte-based. |
Object testPayload = ...
template.sendBodyAndHeader("direct:create-and-write-to-persistent-znode", testPayload, "CamelZookeeperCreateMode", "PERSISTENT");