[[infinispan-component]]
= Infinispan Component
//THIS FILE IS COPIED: EDIT THE SOURCE FILE:
:page-source: components/camel-infinispan/camel-infinispan/src/main/docs/infinispan-component.adoc
:docTitle: Infinispan
:artifactId: camel-infinispan
:description: Read and write from/to Infinispan distributed key/value store and data grid.
:since: 2.13
:supportLevel: Stable
:component-header: Both producer and consumer are supported
include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/infinispan.adoc[opts=optional]

*Since Camel {since}*

*{component-header}*

This component allows you to interact with http://infinispan.org/[Infinispan] distributed data grid / cache using the Hot Rod procol.
Infinispan is an extremely scalable, highly available key/value data store and data grid platform written in Java.

Infinispan requires at least Java 8.

If you use Maven, you must add the following dependency to your `pom.xml`:

[source,xml]
------------------------------------------------------------
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-infinispan</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>
------------------------------------------------------------

== URI format

[source,java]
-------------------------------
infinispan://cacheName?[options]
-------------------------------

== URI Options

The producer allows sending messages to a remote cache using the HotRod protocol. 
The consumer allows listening for events from a remote cache using the HotRod protocol.

// component options: START
The Infinispan component supports 26 options, which are listed below.



[width="100%",cols="2,5,^1,2",options="header"]
|===
| Name | Description | Default | Type
| *configuration* (common) | Component configuration |  | InfinispanRemoteConfiguration
| *hosts* (common) | Specifies the host of the cache on Infinispan instance |  | String
| *queryBuilder* (common) | Specifies the query builder. |  | InfinispanQueryBuilder
| *secure* (common) | Define if we are connecting to a secured Infinispan instance | false | boolean
| *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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
| *customListener* (consumer) | Returns the custom listener in use, if provided |  | InfinispanRemoteCustomListener
| *eventTypes* (consumer) | Specifies the set of event types to register by the consumer.Multiple event can be separated by comma. The possible event types are: CLIENT_CACHE_ENTRY_CREATED, CLIENT_CACHE_ENTRY_MODIFIED, CLIENT_CACHE_ENTRY_REMOVED, CLIENT_CACHE_ENTRY_EXPIRED, CLIENT_CACHE_FAILOVER |  | String
| *defaultValue* (producer) | Set a specific default value for some producer operations |  | Object
| *key* (producer) | Set a specific key for producer operations |  | Object
| *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
| *oldValue* (producer) | Set a specific old value for some producer operations |  | Object
| *operation* (producer) | The operation to perform. There are 21 enums and the value can be one of: PUT, PUTASYNC, PUTALL, PUTALLASYNC, PUTIFABSENT, PUTIFABSENTASYNC, GET, GETORDEFAULT, CONTAINSKEY, CONTAINSVALUE, REMOVE, REMOVEASYNC, REPLACE, REPLACEASYNC, SIZE, CLEAR, CLEARASYNC, QUERY, STATS, COMPUTE, COMPUTEASYNC | PUT | InfinispanOperation
| *value* (producer) | Set a specific value for producer operations |  | Object
| *password* ( security) | Define the password to access the infinispan instance |  | String
| *saslMechanism* ( security) | Define the SASL Mechanism to access the infinispan instance |  | String
| *securityRealm* ( security) | Define the security realm to access the infinispan instance |  | String
| *securityServerName* ( security) | Define the security server name to access the infinispan instance |  | String
| *username* ( security) | Define the username to access the infinispan instance |  | String
| *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
| *cacheContainer* (advanced) | *Autowired* Specifies the cache Container to connect |  | RemoteCacheManager
| *cacheContainerConfiguration* (advanced) | *Autowired* The CacheContainer configuration. Used if the cacheContainer is not defined. |  | Configuration
| *configurationProperties* (advanced) | Implementation specific properties for the CacheManager |  | Map
| *configurationUri* (advanced) | An implementation specific URI for the CacheManager |  | String
| *flags* (advanced) | A comma separated list of org.infinispan.client.hotrod.Flag to be applied by default on each cache invocation. |  | String
| *remappingFunction* (advanced) | Set a specific remappingFunction to use in a compute operation. |  | BiFunction
| *resultHeader* (advanced) | Store the operation result in a header instead of the message body. By default, resultHeader == null and the query result is stored in the message body, any existing content in the message body is discarded. If resultHeader is set, the value is used as the name of the header to store the query result and the original message body is preserved. This value can be overridden by an in message header named: CamelInfinispanOperationResultHeader |  | String
|===
// component options: END




// endpoint options: START
The Infinispan endpoint is configured using URI syntax:

----
infinispan:cacheName
----

with the following path and query parameters:

=== Path Parameters (1 parameters):


[width="100%",cols="2,5,^1,2",options="header"]
|===
| Name | Description | Default | Type
| *cacheName* | *Required* The name of the cache to use. Use current to use the existing cache name from the currently configured cached manager. Or use default for the default cache manager name. |  | String
|===


=== Query Parameters (26 parameters):


[width="100%",cols="2,5,^1,2",options="header"]
|===
| Name | Description | Default | Type
| *hosts* (common) | Specifies the host of the cache on Infinispan instance |  | String
| *queryBuilder* (common) | Specifies the query builder. |  | InfinispanQueryBuilder
| *secure* (common) | Define if we are connecting to a secured Infinispan instance | false | boolean
| *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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
| *customListener* (consumer) | Returns the custom listener in use, if provided |  | InfinispanRemoteCustomListener
| *eventTypes* (consumer) | Specifies the set of event types to register by the consumer.Multiple event can be separated by comma. The possible event types are: CLIENT_CACHE_ENTRY_CREATED, CLIENT_CACHE_ENTRY_MODIFIED, CLIENT_CACHE_ENTRY_REMOVED, CLIENT_CACHE_ENTRY_EXPIRED, CLIENT_CACHE_FAILOVER |  | String
| *exceptionHandler* (consumer) | 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) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut |  | ExchangePattern
| *defaultValue* (producer) | Set a specific default value for some producer operations |  | Object
| *key* (producer) | Set a specific key for producer operations |  | Object
| *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
| *oldValue* (producer) | Set a specific old value for some producer operations |  | Object
| *operation* (producer) | The operation to perform. There are 21 enums and the value can be one of: PUT, PUTASYNC, PUTALL, PUTALLASYNC, PUTIFABSENT, PUTIFABSENTASYNC, GET, GETORDEFAULT, CONTAINSKEY, CONTAINSVALUE, REMOVE, REMOVEASYNC, REPLACE, REPLACEASYNC, SIZE, CLEAR, CLEARASYNC, QUERY, STATS, COMPUTE, COMPUTEASYNC | PUT | InfinispanOperation
| *value* (producer) | Set a specific value for producer operations |  | Object
| *password* ( security) | Define the password to access the infinispan instance |  | String
| *saslMechanism* ( security) | Define the SASL Mechanism to access the infinispan instance |  | String
| *securityRealm* ( security) | Define the security realm to access the infinispan instance |  | String
| *securityServerName* ( security) | Define the security server name to access the infinispan instance |  | String
| *username* ( security) | Define the username to access the infinispan instance |  | String
| *cacheContainer* (advanced) | *Autowired* Specifies the cache Container to connect |  | RemoteCacheManager
| *cacheContainerConfiguration* (advanced) | *Autowired* The CacheContainer configuration. Used if the cacheContainer is not defined. |  | Configuration
| *configurationProperties* (advanced) | Implementation specific properties for the CacheManager |  | Map
| *configurationUri* (advanced) | An implementation specific URI for the CacheManager |  | String
| *flags* (advanced) | A comma separated list of org.infinispan.client.hotrod.Flag to be applied by default on each cache invocation. |  | String
| *remappingFunction* (advanced) | Set a specific remappingFunction to use in a compute operation. |  | BiFunction
| *resultHeader* (advanced) | Store the operation result in a header instead of the message body. By default, resultHeader == null and the query result is stored in the message body, any existing content in the message body is discarded. If resultHeader is set, the value is used as the name of the header to store the query result and the original message body is preserved. This value can be overridden by an in message header named: CamelInfinispanOperationResultHeader |  | String
|===
// endpoint options: END

== Camel Operations
This section lists all available operations, along with their header information.

.Put Operations
[cols="40%,60%a", frame="all", options="header"]
|===
| Operation Name | Description
| InfinispanOperation.PUT | Puts a key/value pair in the cache, optionally with expiration
| InfinispanOperation.PUTASYNC | Asynchronously puts a key/value pair in the cache, optionally with expiration
| InfinispanOperation.PUTIFABSENT | Puts a key/value pair in the cache if it did not exist, optionally with expiration
| InfinispanOperation.PUTIFABSENTASYNC | Asynchronously puts a key/value pair in the cache if it did not exist, optionally with expiration
|===

* *Required Headers*: 
** CamelInfinispanKey
** CamelInfinispanValue
* *Optional Headers*: 
** CamelInfinispanLifespanTime
** CamelInfinispanLifespanTimeUnit
** CamelInfinispanMaxIdleTime
** CamelInfinispanMaxIdleTimeUnit
* *Result Header*: 
** CamelInfinispanOperationResult

.Put All Operations
[cols="40%,60%a", options="header"]
|===
| Operation Name | Description
| InfinispanOperation.PUTALL | Adds multiple entries to a cache, optionally with expiration
| CamelInfinispanOperation.PUTALLASYNC | Asynchronously adds multiple entries to a cache, optionally with expiration
|===

* *Required Headers*: 
** CamelInfinispanMap
* *Optional Headers*: 
** CamelInfinispanLifespanTime
** CamelInfinispanLifespanTimeUnit
** CamelInfinispanMaxIdleTime
** CamelInfinispanMaxIdleTimeUnit

.Get Operations
[cols="40%,60%a", frame="all", options="header"]
|===
|Operation Name |Description
| InfinispanOperation.GET | Retrieves the value associated with a specific key from the cache
| InfinispanOperation.GETORDEFAULT | Retrieves the value, or default value, associated with a specific key from the cache
|===

* *Required Headers*: 
** CamelInfinispanKey

.Contains Key Operation
[cols="40%,60%a", options="header"]
|===
| Operation Name | Description
| InfinispanOperation.CONTAINSKEY | Determines whether a cache contains a specific key
|===

* *Required Headers*
** CamelInfinispanKey
* *Result Header*
** CamelInfinispanOperationResult

.Contains Value Operation
[cols="40%,60%a", options="header"]
|===
| Operation Name | Description
| InfinispanOperation.CONTAINSVALUE | Determines whether a cache contains a specific value
|===

* *Required Headers*: 
** CamelInfinispanKey


.Remove Operations
[cols="40%,60%a", options="header"]
|===
| Operation Name | Description
| InfinispanOperation.REMOVE | Removes an entry from a cache, optionally only if the value matches a given one
| InfinispanOperation.REMOVEASYNC | Asynchronously removes an entry from a cache, optionally only if the value matches a given one
|===

* *Required Headers*:
** CamelInfinispanKey
* *Optional Headers*: 
** CamelInfinispanValue
* *Result Header*: 
** CamelInfinispanOperationResult

.Replace Operations
[cols="40%,60%a", options="header"]
|===
| Operation Name | Description
| InfinispanOperation.REPLACE | Conditionally replaces an entry in the cache, optionally with expiration
| InfinispanOperation.REPLACEASYNC |  Asynchronously conditionally replaces an entry in the cache, optionally with expiration
|===

* *Required Headers*: 
** CamelInfinispanKey
** CamelInfinispanValue
** CamelInfinispanOldValue
* *Optional Headers*:
** CamelInfinispanLifespanTime
** CamelInfinispanLifespanTimeUnit
** CamelInfinispanMaxIdleTime
** CamelInfinispanMaxIdleTimeUnit
* *Result Header*: 
** CamelInfinispanOperationResult

.Clear Operations
[cols="40%,60%a", options="header"]
|===
| Operation Name | Description
| InfinispanOperation.CLEAR | Clears the cache
| InfinispanOperation.CLEARASYNC | Asynchronously clears the cache
|===

.Size Operation
[cols="40%,60%a", options="header"]
|===
| Operation Name | Description
| InfinispanOperation.SIZE | Returns the number of entries in the cache
|===

* *Result Header*
** CamelInfinispanOperationResult

.Stats Operation
[cols="40%,60%a", options="header"]
|===
| Operation Name | Description
| InfinispanOperation.STATS | Returns statistics about the cache
|===

* *Result Header*:
** CamelInfinispanOperationResult

.Query Operation
[cols="40%,60%a", options="header"]
|===
| Operation Name | Description
| InfinispanOperation.QUERY | Executes a query on the cache
|===

* *Required Headers*:
** CamelInfinispanQueryBuilder
* *Result Header*: 
** CamelInfinispanOperationResult

[NOTE]
====
Write methods like put(key, value) and remove(key) do not return the previous value by default.
====

== Message Headers

[width="100%",cols="10%,10%,10%,10%,60%",options="header",]
|=======================================================================
|Name |Default Value |Type |Context |Description
|CamelInfinispanCacheName |`null` |String |Shared |The cache participating in the operation or event.
|CamelInfinispanOperation |`PUT` |InfinispanOperation |Producer |The operation to perform.
|CamelInfinispanMap |`null` |Map |Producer |A Map to use in case of CamelInfinispanOperationPutAll operation
|CamelInfinispanKey |`null` |Object |Shared |The key to perform the operation to or the key generating the event.
|CamelInfinispanValue |`null` |Object |Producer |The value to use for the operation.
|CamelInfinispanEventType |`null` |String |Consumer |The type of the received event. 
|CamelInfinispanLifespanTime |`null` |long |Producer |The Lifespan time of a value inside the cache. Negative values are interpreted as infinity.
|CamelInfinispanTimeUnit |`null` |String |Producer |The Time Unit of an entry Lifespan Time.
|CamelInfinispanMaxIdleTime |`null` |long |Producer |The maximum amount of time an entry is allowed to be idle for before it is considered as expired.
|CamelInfinispanMaxIdleTimeUnit |`null` |String |Producer |The Time Unit of an entry Max Idle Time.
|CamelInfinispanQueryBuilder |null |InfinispanQueryBuilder |Producer |The QueryBuilde to use for QUERY command, if not present the command defaults to InifinispanConfiguration's one
|CamelInfinispanOperationResultHeader |null |String |Producer |Store the operation result in a header instead of the message body
|=======================================================================


== Examples

* Put a key/value into a named cache:
+
[source,java]
----
from("direct:start")
    .setHeader(InfinispanConstants.OPERATION).constant(InfinispanOperation.PUT) // <1>
    .setHeader(InfinispanConstants.KEY).constant("123") // <2>
    .to("infinispan:myCacheName&cacheContainer=#cacheContainer"); // <3>
----
<1> Set the operation to perform
<2> Set the key used to identify the element in the cache
<3> Use the configured cache manager `cacheContainer` from the registry to put an element to the cache named `myCacheName`
+
It is possible to configure the lifetime and/or the idle time before the entry expires and gets evicted from the cache, as example:
+
[source,java,options="nowrap"]
----
from("direct:start")
    .setHeader(InfinispanConstants.OPERATION).constant(InfinispanOperation.GET)
    .setHeader(InfinispanConstants.KEY).constant("123")
    .setHeader(InfinispanConstants.LIFESPAN_TIME).constant(100L) // <1>
    .setHeader(InfinispanConstants.LIFESPAN_TIME_UNIT.constant(TimeUnit.MILLISECONDS.toString()) // <2>
    .to("infinispan:myCacheName");
----
<1> Set the lifespan of the entry
<2> Set the time unit for the lifespan

* Queries
+
[source,java,options="nowrap"]
----
from("direct:start")
    .setHeader(InfinispanConstants.OPERATION, InfinispanConstants.QUERY)
    .setHeader(InfinispanConstants.QUERY_BUILDER, new InfinispanQueryBuilder() {
        @Override
        public Query build(QueryFactory<Query> qf) {
            return qf.from(User.class).having("name").like("%abc%").build();
        }
    })
    .to("infinispan:myCacheName?cacheContainer=#cacheManager") ;
----
+

[NOTE]
====
The .proto descriptors for domain objects must be registered with the remote Data Grid server, see https://infinispan.org/docs/stable/titles/developing/developing.html#remote_query_example[Remote Query Example] in the official Infinispan documentation.
====

* Custom Listeners
+
[source,java,options="nowrap"]
----
from("infinispan://?cacheContainer=#cacheManager&customListener=#myCustomListener")
  .to("mock:result");
----
+
The instance of `myCustomListener` must exist and Camel should be able to look it up from the  `Registry`.
Users are encouraged to extend the `org.apache.camel.component.infinispan.remote.InfinispanRemoteCustomListener` class and annotate the resulting class with `@ClientListener` which can be found found in package `org.infinispan.client.hotrod.annotation`.


== Using the Infinispan based idempotent repository

In this section we will use the Infinispan based idempotent repository.

.Java Example
[source,java]
----
InfinispanRemoteConfiguration conf = new InfinispanRemoteConfiguration(); // <1> 
conf.setHosts("localhost:1122")

InfinispanRemoteIdempotentRepository repo = new InfinispanRemoteIdempotentRepository("idempotent");  // <2> 
repo.setConfiguration(conf);

context.addRoutes(new RouteBuilder() {
    @Override
    public void configure() {
        from("direct:start")
            .idempotentConsumer(header("MessageID"), repo) // <3> 
            .to("mock:result");
    }
});
----
<1> Configure the cache
<2> Configure the repository bean
<3> Set the repository to the route

.XML Example
[source,xml]
----
<bean id="infinispanRepo" class="org.apache.camel.component.infinispan.remote.InfinispanRemoteIdempotentRepository" destroy-method="stop">
  <constructor-arg value="idempotent"/> <1>
  <property name="configuration"> <2>
    <bean class="org.apache.camel.component.infinispan.remote.InfinispanRemoteConfiguration">
      <property name="hosts" value="localhost:11222"/>
    </bean>
  </property>
</bean>

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:start" />
        <idempotentConsumer messageIdRepositoryRef="infinispanRepo"> <3>
            <header>MessageID</header>
            <to uri="mock:result" />
        </idempotentConsumer>
    </route>
</camelContext>
----
<1> Set the name of the cache that will be used by the repository
<2> Configure the repository bean
<3> Set the repository to the route

== Using the Infinispan based aggregation repository

In this section we will use the Infinispan based aggregation repository.

.Java Example
[source,java]
----
InfinispanRemoteConfiguration conf = new InfinispanRemoteConfiguration(); // <1> 
conf.setHosts("localhost:1122")

InfinispanRemoteAggregationRepository repo = new InfinispanRemoteAggregationRepository();  // <2> 
repo.setCacheName("aggregation");
repo.setConfiguration(conf);

context.addRoutes(new RouteBuilder() {
    @Override
    public void configure() {
        from("direct:start")
                .aggregate(header("MessageID"))
                .completionSize(3)
                .aggregationRepository(repo) // <3>
                .aggregationStrategyRef("myStrategy")
                .to("mock:result");
    }
});
----
<1> Configure the cache
<2> Create the repository bean
<3> Set the repository to the route

.XML Example
[source,xml]
----
<bean id="infinispanRepo" class="org.apache.camel.component.infinispan.remote.InfinispanRemoteAggregationRepository" destroy-method="stop">
  <constructor-arg value="aggregation"/> <1>
  <property name="configuration"> <2>
    <bean class="org.apache.camel.component.infinispan.remote.InfinispanRemoteConfiguration">
      <property name="hosts" value="localhost:11222"/>
    </bean>
  </property>
</bean>

<camelContext xmlns="http://camel.apache.org/schema/spring">
    <route>
        <from uri="direct:start" />
        <aggregate strategyRef="myStrategy"   
                   completionSize="3"
                   aggregationRepositoryRef="infinispanRepo"> <3>
            <correlationExpression>
                <header>MessageID</header>
            </correlationExpression>
            <to uri="mock:result"/>
        </aggregate>
    </route>
</camelContext>
----
<1> Set the name of the cache that will be used by the repository
<2> Configure the repository bean
<3> Set the repository to the route

[NOTE]
====
With the release of Infinispan 11, it is required to set the encoding configuration on any cache created. This is critical for consuming events too.
For more information have a look at https://infinispan.org/docs/stable/titles/developing/developing.html#data_encoding[Data Encoding and MediaTypes] in the official Infinispan documentation.
====




include::{page-component-version}@camel-spring-boot::page$infinispan-starter.adoc[]
