Infinispan 8 tutorial

In this tutorial you will learn how to configure and use Infinispan 8.1 and use some of its API.

The server version of Infinispan is available at: http://infinispan.org/download/

Behind the hoods the new server version is bundled into a WildFly installation, therefore you will have to configure Infinispan through the infinispan subsystem. The standalone server contains two configurations:

  • standalone.xml (non-clustered cache)
  • clustered.xml (clustered Infinispan distribution)

Here follows the clustered configuration:

<subsystem xmlns="urn:infinispan:server:core:8.1" default-cache-container="clustered">
    <cache-container name="clustered" default-cache="default" statistics="true">
        <transport lock-timeout="60000"/>
        <distributed-cache name="default" mode="SYNC" segments="20" owners="2" remote-timeout="30000" start="EAGER">
            <locking acquire-timeout="30000" concurrency-level="1000" striping="false"/>
            <transaction mode="NONE"/>
        </distributed-cache>
        <distributed-cache name="memcachedCache" mode="SYNC" segments="20" owners="2" remote-timeout="30000" start="EAGER">
            <locking acquire-timeout="30000" concurrency-level="1000" striping="false"/>
            <transaction mode="NONE"/>
        </distributed-cache>
        <distributed-cache name="namedCache" mode="SYNC" start="EAGER"/>
        <distributed-cache name="transactionalCache" mode="SYNC" start="EAGER">
            <transaction mode="NON_XA" locking="PESSIMISTIC"/>
        </distributed-cache>
    </cache-container>
</subsystem>

Basically, Infinispan offers two access patterns, both of which are available in any runtime:

  • Embedded into your application code
  • As a Remote server accessed by a client (REST, memcached or Hot Rod wire protocols are supported)

In the latter case, you will need some connectors which enable receiving calls from remote clients:

<subsystem xmlns="urn:infinispan:server:endpoint:8.0">
    <hotrod-connector socket-binding="hotrod" cache-container="clustered">
        <topology-state-transfer lazy-retrieval="false" lock-timeout="1000" replication-timeout="5000"/>
    </hotrod-connector>
    <memcached-connector socket-binding="memcached" cache-container="clustered"/>
    <rest-connector socket-binding="rest" cache-container="clustered" security-domain="other" auth-method="BASIC"/>
    <websocket-connector socket-binding="websocket" cache-container="clustered"/>
</subsystem>

Let's see as an example an HotRod client application which connects to the "default" clustered caches, and adds some data to it. At first we will start a cluster of Infinispan nodes. This can be easily achieved starting the server in domain mode, which is bound to the "clustered" profile.

$ domain.sh

Check from the logs that the server started and that the clusted was correclty composed:

[Server:server-one] 19:47:03,254 INFO [org.infinispan.CLUSTER] (remote-thread--p2-t4) ISPN000310: Starting cluster-wide rebalance for cache ___hotRodTopologyCache, topology CacheTopology{id=1, rebalanceId=1, currentCH=ReplicatedConsistentHash{ns = 60, owners = (1)[master:server-one: 60]}, pendingCH=ReplicatedConsistentHash{ns = 60, owners = (2)[master:server-one: 30, master:server-two: 30]}, unionCH=null, actualMembers=[master:server-one, master:server-two]}

Now let's connect to the Infinispan cluster with some code:

package com.mastertheboss;

import java.util.Iterator;
import java.util.Map;

import java.util.Set;
import java.util.UUID;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.ServerStatistics;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;

public class DemoHotRod {

    private RemoteCacheManager cacheManager;
    private RemoteCache<String, Object> cache;

    public DemoHotRod() {

        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.addServer()
                .host("127.0.0.1")
                .port(Integer.parseInt("11222"));
        cacheManager = new RemoteCacheManager(builder.build());

        cache = cacheManager.getCache("default");

        cache.put(UUID.randomUUID().toString(), UUID.randomUUID().toString());

        System.out.println("Dumping cache Data");
        System.out.println("==========================");
        Set set = this.cache.keySet();
        Iterator i = set.iterator();
        while (i.hasNext()) {
            System.out.println(i.next());
        }
        //Print cache statistics
        ServerStatistics stats = cache.stats();
        for (Map.Entry stat : stats.getStatsMap().entrySet()) {
            System.out.println(stat.getKey() + " : " + stat.getValue());
        }

    }

    public static void main(String[] args) {

        DemoHotRod manager = new DemoHotRod();

    }

}

In order to compile the class, you will need to incude the Infinispan core libraries and the Hot Rod client APIs, plus their dependencies. The simplest way to do that is by means of the following Maven's pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mastertheboss</groupId>
    <artifactId>hotrod-demo</artifactId>
    <version>1.0.0</version>
    <name>Hot Rod Client Demo</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
 
        <version.org.infinispan>8.0.1.Final</version.org.infinispan>

        <!-- other plugin versions -->
        <exec.plugin.version>1.2.1</exec.plugin.version>
        <ant.plugin.version>1.7</ant.plugin.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.infinispan</groupId>
                <artifactId>infinispan-bom</artifactId>
                <version>${version.org.infinispan}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <!-- Import the infinispan core -->
        <dependency>
            <groupId>org.infinispan</groupId>
            <artifactId>infinispan-core</artifactId>
            <scope>compile</scope>
        </dependency>

        <!-- Import the Infinispan client hotrod -->
        <dependency>
            <groupId>org.infinispan</groupId>
            <artifactId>infinispan-client-hotrod</artifactId>
            <scope>compile</scope>
        </dependency>
    </dependencies>

    <build>
        <!-- Maven will append the version to the finalName (which is the 
            name given to the generated jar) -->
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!-- This plugin permits the execution of this quickstart 
                through mvn exec:java command -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>${exec.plugin.version}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>java</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>com.mastertheboss.DemoHotRod</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
</project>

You can compile the class with:

$ mvn clean install

And run the application with:

$ mvn exec:java

As a result, you should see in your cache an entry named

Dumping cache Data
==========================
153ccf2e-5aee-4de5-95bc-afe9d941deb4

currentNumberOfEntries : 1
hits : 0
removeHits : 0
totalBytesRead : 15
timeSinceStart : 214
removeMisses : 0
totalNumberOfEntries : 0
stores : 0
misses : 0
retrievals : 0
totalBytesWritten : 0

Related articles available on mastertheboss.com

Follow us on Twitter