Chapter 1. The Cache API
The Cache interface provides simple methods for the addition, retrieval and removal of entries, which includes atomic mechanisms exposed by the JDK's
ConcurrentMap
interface. How entries are stored depends on the cache mode in use. For example, an entry may be replicated to a remote node or an entry may be looked up in a cache store.
The Cache API is used in the same manner as the JDK Map API for basic tasks. This simplifies the process of migrating from Map-based, simple in-memory caches to Red Hat JBoss Data Grid's cache.
Note
This API is not available in JBoss Data Grid's Remote Client-Server Mode
1.1. Using the ConfigurationBuilder API to Configure the Cache API
Red Hat JBoss Data Grid uses a ConfigurationBuilder API to configure caches.
Caches are configured programmatically using the
ConfigurationBuilder
helper object.
The following is an example of a synchronously replicated cache configured programmatically using the ConfigurationBuilder API:
Example 1.1. Programmatic Cache Configuration
Configuration c = new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_SYNC).build(); String newCacheName = "repl"; manager.defineConfiguration(newCacheName, c); Cache<String, String> cache = manager.getCache(newCacheName);
Configuration Explanation:
An explanation of each line of the provided configuration is as follows:
Configuration c = new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_SYNC).build();
In the first line of the configuration, a new cache configuration object (namedc
) is created using theConfigurationBuilder
. Configurationc
is assigned the default values for all cache configuration options except the cache mode, which is overridden and set to synchronous replication (REPL_SYNC
).String newCacheName = "repl";
In the second line of the configuration, a new variable (of typeString
) is created and assigned the valuerepl
.manager.defineConfiguration(newCacheName, c);
In the third line of the configuration, the cache manager is used to define a named cache configuration for itself. This named cache configuration is calledrepl
and its configuration is based on the configuration provided for cache configurationc
in the first line.Cache<String, String> cache = manager.getCache(newCacheName);
In the fourth line of the configuration, the cache manager is used to obtain a reference to the unique instance of therepl
that is held by the cache manager. This cache instance is now ready to be used to perform operations to store and retrieve data.
Note
JBoss EAP includes its own underlying JMX. This can cause a collision when using the sample code with JBoss EAP and display an error such as
org.infinispan.jmx.JmxDomainConflictException: Domain already registered org.infinispan
.
To avoid this, configure global configuration as follows:
GlobalConfiguration glob = new GlobalConfigurationBuilder() .clusteredDefault() .globalJmxStatistics() .allowDuplicateDomains(true) .enable() .build();