Camel Components

Hazelcast Map

Since Camel 2.7

Both producer and consumer are supported

The Hazelcast Map component is one of Camel Hazelcast Components which allows you to access a Hazelcast distributed map.

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 Hazelcast Map component supports the following options which are listed below.

Name Description Default Type

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (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

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

hazelcastInstance (advanced)

The Hazelcast instance that the endpoints of this component use when they set none of hazelcastInstance, hazelcastInstanceName, hazelcastConfig and hazelcastConfigUri. Without it, Camel starts a Hazelcast instance for each such endpoint, with the configuration that Hazelcast finds itself (a hazelcast.xml file, or hazelcast-client.xml in client mode, or else the Hazelcast defaults), and shuts it down when the component stops.

HazelcastInstance

hazelcastMode (advanced)

Whether the endpoints start or look up a Hazelcast member (node) or a Hazelcast client (client): in client mode hazelcastInstanceName names a client, and hazelcastConfigUri and hazelcastConfig give a client configuration. Any value other than node means client.

node

String

Endpoint Options

The Hazelcast Map endpoint is configured using URI syntax:

hazelcast-map:cacheName

With the following path and query parameters:

Path Parameters

Name Description Default Type

cacheName (common)

Required The name of the Hazelcast data structure: the map, multimap, replicated map, list, set, queue, topic, ringbuffer or PN counter, or the queue of hazelcast-seda. hazelcast-instance does not use it.

String

Query Parameters

Name Description Default Type

defaultOperation (common)

The operation to perform when the message has no CamelHazelcastOperationType header. Each data structure supports only some of the operations, and another one fails. hazelcast-queue uses add and hazelcast-topic publish when it is not set, and the producers of the other data structures fail without an operation. hazelcast-seda and hazelcast-instance do not use it.

Enum values:

  • put

  • delete

  • get

  • update

  • query

  • getAll

  • clear

  • putIfAbsent

  • addAll

  • removeAll

  • retainAll

  • evict

  • evictAll

  • valueCount

  • containsKey

  • containsValue

  • getKeys

  • removeValue

  • increment

  • decrement

  • setValue

  • destroy

  • compareAndSet

  • getAndAdd

  • add

  • offer

  • peek

  • poll

  • remainingCapacity

  • drainTo

  • removeIf

  • take

  • publish

  • readOnceHead

  • readOnceTail

  • capacity

HazelcastOperation

hazelcastConfigUri (common)

The location of a Hazelcast XML configuration file (a client configuration when hazelcastMode is client), from which Camel starts a Hazelcast instance for the endpoint. A member configuration that sets an instance name reuses the running member of that name. The file is on the classpath by default; use the file: prefix for a file. Used only when neither hazelcastInstance nor hazelcastInstanceName gives an instance, and when hazelcastConfig is not set.

String

hazelcastInstance (common)

The Hazelcast instance to use. It takes precedence over hazelcastInstanceName, hazelcastConfig, hazelcastConfigUri and the hazelcastInstance option of the component. Camel does not shut it down.

HazelcastInstance

hazelcastInstanceName (common)

The name of a Hazelcast instance that is already running in this JVM: a member, or a client when hazelcastMode is client. It takes precedence over hazelcastConfig and hazelcastConfigUri. When no instance has this name, the endpoint gets its instance as if this option was not set.

String

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

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

Message Headers

The Hazelcast Map component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelHazelcastObjectId (common)

Constant: OBJECT_ID

The key of the entry: the producer of a map, multimap or replicated map uses it for the operations on a key (a Set of keys for the getAll operation of a map) and removes the header afterwards, and their consumers set it to the key of the entry of the event.

String

CamelHazelcastObjectValue (producer)

Constant: OBJECT_VALUE

The value that the update operation expects the key to have: when set, update replaces the value only if the key currently has this value.

Object

CamelHazelcastObjectTtlValue (producer)

Constant: TTL_VALUE

The time to live of the entry for the put and putIfAbsent operations, as a Long, in the unit of the CamelHazelcastObjectTtlUnit header: set both headers. 0 means the entry does not expire, and a negative value means the time to live of the map configuration.

Integer

CamelHazelcastObjectTtlUnit (producer)

Constant: TTL_UNIT

The TimeUnit of the CamelHazelcastObjectTtlValue header, for the put and putIfAbsent operations.

Enum values:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

TimeUnit

CamelHazelcastQuery (producer)

Constant: QUERY

The predicate of the query operation, in the SQL-like syntax of a Hazelcast SqlPredicate, such as active AND age > 30: query returns the values that match it, or all values without the header.

String

CamelHazelcastListenerAction (consumer)

Constant: LISTENER_ACTION

The kind of event: added, removed, updated, evicted or expired for an entry of a map, multimap or replicated map, added or removed for an item of a list, set or queue and for a member of the cluster (hazelcast-instance), and received for a message of a topic.

String

CamelHazelcastListenerType (consumer)

Constant: LISTENER_TYPE

The type of listener that received the event: instancelistener for hazelcast-instance, and cachelistener for the other consumers.

String

CamelHazelcastListenerTime (consumer)

Constant: LISTENER_TIME

The time when the consumer received the event, in milliseconds since the epoch.

Long

CamelHazelcastCacheName (consumer)

Constant: CACHE_NAME

The name of the data structure that the event comes from: the cacheName of the endpoint.

String

CamelHazelcastOperationType (producer)

Constant: OPERATION

The operation to perform, such as put or get, by its name or as a HazelcastOperation: it overrides the defaultOperation option. The producer removes the header afterwards.

String

Message Body

The message body at each side of the Hazelcast Map 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

unknown

The value of the entry for an added or updated event, as any member of the cluster stored it, and no body for removed, evicted and expired (the time to live of the entry ended): the key is in the CamelHazelcastObjectId header and the event in CamelHazelcastListenerAction.

Producer input

text, bytes, file, value, map, list or pojo

The value that put, putIfAbsent and update store under the key in the CamelHazelcastObjectId header, and that containsValue looks for: an object Hazelcast can serialize, so a stream fails (convert it to bytes or text first), and no body fails. The other operations do not use the body.

Producer output

unknown

By the operation, which the CamelHazelcastOperationType header sets, or else the defaultOperation option (without either the producer fails): the value of the key for get, or null when the key is not in the map, a Map of the keys in the Set of the CamelHazelcastObjectId header to their values for getAll, the keys for getKeys and the values that match the SQL predicate of the CamelHazelcastQuery header for query as a Collection, and a Boolean for containsKey and containsValue. The other operations keep the body.

  • With defaultOperation=put: unchanged

  • With defaultOperation=putIfAbsent: unchanged

  • With defaultOperation=update: unchanged

  • With defaultOperation=delete: unchanged

  • With defaultOperation=evict: unchanged

  • With defaultOperation=evictAll: unchanged

  • With defaultOperation=clear: unchanged

  • With defaultOperation=containsKey: value (java.lang.Boolean)

  • With defaultOperation=containsValue: value (java.lang.Boolean)

  • With defaultOperation=getAll: map

  • With defaultOperation=getKeys: list

  • With defaultOperation=query: 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.

Map cache producer - to("hazelcast-map:foo")

If you want to store a value in a map, you can use the map cache producer.

The map cache producer provides follow operations specified by CamelHazelcastOperationType header:

  • put

  • putIfAbsent

  • get

  • getAll

  • keySet

  • containsKey

  • containsValue

  • delete

  • update

  • query

  • clear

  • evict

  • evictAll

You can call the samples with:

Java-only: calling producer operations using ProducerTemplate
template.sendBodyAndHeader("direct:[put|get|update|delete|query|evict]", "my-foo", "CamelHazelcastObjectId", "4711");

Example for put:

  • Java

  • XML

  • YAML

from("direct:put")
.setHeader("CamelHazelcastOperationType", constant("put"))
.to("hazelcast-map:foo");
<route>
    <from uri="direct:put"/>
    <setHeader name="CamelHazelcastOperationType">
        <constant>put</constant>
    </setHeader>
    <to uri="hazelcast-map:foo"/>
</route>
- route:
    from:
      uri: direct:put
      steps:
        - setHeader:
            name: CamelHazelcastOperationType
            constant: put
        - to:
            uri: hazelcast-map:foo

Sample for put with eviction:

  • Java

  • XML

  • YAML

from("direct:put")
.setHeader("CamelHazelcastOperationType", constant("put"))
.setHeader("CamelHazelcastObjectTtlValue", constant(Long.valueOf(1)))
.setHeader("CamelHazelcastObjectTtlUnit", constant(TimeUnit.MINUTES))
.to("hazelcast-map:foo");
<route>
    <from uri="direct:put"/>
    <setHeader name="CamelHazelcastOperationType">
        <constant>put</constant>
    </setHeader>
    <setHeader name="CamelHazelcastObjectTtlValue">
        <constant>1</constant>
    </setHeader>
    <setHeader name="CamelHazelcastObjectTtlUnit">
        <constant>MINUTES</constant>
    </setHeader>
    <to uri="hazelcast-map:foo"/>
</route>
- route:
    from:
      uri: direct:put
      steps:
        - setHeader:
            name: CamelHazelcastOperationType
            constant: put
        - setHeader:
            name: CamelHazelcastObjectTtlValue
            constant: "1"
        - setHeader:
            name: CamelHazelcastObjectTtlUnit
            constant: MINUTES
        - to:
            uri: hazelcast-map:foo

Example for get:

  • Java

  • XML

  • YAML

from("direct:get")
.setHeader("CamelHazelcastOperationType", constant("get"))
.to("hazelcast-map:foo")
.to("seda:out");
<route>
    <from uri="direct:get"/>
    <setHeader name="CamelHazelcastOperationType">
        <constant>get</constant>
    </setHeader>
    <to uri="hazelcast-map:foo"/>
    <to uri="seda:out"/>
</route>
- route:
    from:
      uri: direct:get
      steps:
        - setHeader:
            name: CamelHazelcastOperationType
            constant: get
        - to:
            uri: hazelcast-map:foo
        - to:
            uri: seda:out

Example for update:

  • Java

  • XML

  • YAML

from("direct:update")
.setHeader("CamelHazelcastOperationType", constant("update"))
.to("hazelcast-map:foo");
<route>
    <from uri="direct:update"/>
    <setHeader name="CamelHazelcastOperationType">
        <constant>update</constant>
    </setHeader>
    <to uri="hazelcast-map:foo"/>
</route>
- route:
    from:
      uri: direct:update
      steps:
        - setHeader:
            name: CamelHazelcastOperationType
            constant: update
        - to:
            uri: hazelcast-map:foo

Example for delete:

  • Java

  • XML

  • YAML

from("direct:delete")
.setHeader("CamelHazelcastOperationType", constant("delete"))
.to("hazelcast-map:foo");
<route>
    <from uri="direct:delete"/>
    <setHeader name="CamelHazelcastOperationType">
        <constant>delete</constant>
    </setHeader>
    <to uri="hazelcast-map:foo"/>
</route>
- route:
    from:
      uri: direct:delete
      steps:
        - setHeader:
            name: CamelHazelcastOperationType
            constant: delete
        - to:
            uri: hazelcast-map:foo

Example for query

  • Java

  • XML

  • YAML

from("direct:query")
.setHeader("CamelHazelcastOperationType", constant("query"))
.to("hazelcast-map:foo")
.to("seda:out");
<route>
    <from uri="direct:query"/>
    <setHeader name="CamelHazelcastOperationType">
        <constant>query</constant>
    </setHeader>
    <to uri="hazelcast-map:foo"/>
    <to uri="seda:out"/>
</route>
- route:
    from:
      uri: direct:query
      steps:
        - setHeader:
            name: CamelHazelcastOperationType
            constant: query
        - to:
            uri: hazelcast-map:foo
        - to:
            uri: seda:out

For the query operation Hazelcast offers an SQL like syntax to query your distributed map.

Java-only: sending a query predicate using ProducerTemplate
String q1 = "bar > 1000";
template.sendBodyAndHeader("direct:query", null, "CamelHazelcastQuery", q1);

Map cache consumer - from("hazelcast-map:foo")

Hazelcast provides event listeners on their data grid. If you want to be notified if a cache is manipulated, you can use the map consumer. There are five events: added, updated, removed, evicted and expired (the time to live of the entry ended). The event type is stored in the CamelHazelcastListenerAction header. The map consumer provides some additional information inside these variables:

Header Variables inside the response message:

Name Type Description

CamelHazelcastListenerTime

Long

time of the event in millis

CamelHazelcastListenerType

String

the map consumer sets here "cachelistener"

CamelHazelcastListenerAction

String

type of event (added, updated, removed, evicted and expired).

CamelHazelcastObjectId

String

the oid of the object

CamelHazelcastCacheName

String

the name of the cache (e.g., "foo")

The object value will be stored within added and updated events inside the message body.

Here’s a sample:

  • Java

  • XML

  • YAML

from("hazelcast-map:foo")
    .log("object...")
    .choice()
        .when(header("CamelHazelcastListenerAction").isEqualTo("added"))
            .log("...added")
            .to("mock:added")
        .when(header("CamelHazelcastListenerAction").isEqualTo("evicted"))
            .log("...evicted")
            .to("mock:evicted")
        .when(header("CamelHazelcastListenerAction").isEqualTo("updated"))
            .log("...updated")
            .to("mock:updated")
        .when(header("CamelHazelcastListenerAction").isEqualTo("removed"))
            .log("...removed")
            .to("mock:removed")
        .otherwise()
            .log("fail!");
<route>
  <from uri="hazelcast-map:foo"/>
  <log message="object..."/>
  <choice>
    <when>
      <simple>${header.CamelHazelcastListenerAction} == 'added'</simple>
      <log message="...added"/>
      <to uri="mock:added"/>
    </when>
    <when>
      <simple>${header.CamelHazelcastListenerAction} == 'evicted'</simple>
      <log message="...evicted"/>
      <to uri="mock:evicted"/>
    </when>
    <when>
      <simple>${header.CamelHazelcastListenerAction} == 'updated'</simple>
      <log message="...updated"/>
      <to uri="mock:updated"/>
    </when>
    <when>
      <simple>${header.CamelHazelcastListenerAction} == 'removed'</simple>
      <log message="...removed"/>
      <to uri="mock:removed"/>
    </when>
    <otherwise>
      <log message="fail!"/>
    </otherwise>
  </choice>
</route>
- route:
    from:
      uri: hazelcast-map:foo
      steps:
        - log:
            message: "object..."
        - choice:
            when:
              - simple: "${header.CamelHazelcastListenerAction} == 'added'"
                steps:
                  - log:
                      message: "...added"
                  - to:
                      uri: mock:added
              - simple: "${header.CamelHazelcastListenerAction} == 'evicted'"
                steps:
                  - log:
                      message: "...evicted"
                  - to:
                      uri: mock:evicted
              - simple: "${header.CamelHazelcastListenerAction} == 'updated'"
                steps:
                  - log:
                      message: "...updated"
                  - to:
                      uri: mock:updated
              - simple: "${header.CamelHazelcastListenerAction} == 'removed'"
                steps:
                  - log:
                      message: "...removed"
                  - to:
                      uri: mock:removed
            otherwise:
              steps:
                - log:
                    message: "fail!"