Chapter 2. Creating embedded caches
Data Grid provides an EmbeddedCacheManager API that lets you control both the Cache Manager and embedded cache lifecycles programmatically.
2.1. Adding Data Grid to your project
Add Data Grid to your project to create embedded caches in your applications.
Prerequisites
- Configure your project to get Data Grid artifacts from the Maven repository.
Procedure
-
Add the
infinispan-coreartifact as a dependency in yourpom.xmlas follows:
<dependencies>
<dependency>
<groupId>org.infinispan</groupId>
<artifactId>infinispan-core</artifactId>
</dependency>
</dependencies>2.2. Configuring embedded caches
Data Grid provides a GlobalConfigurationBuilder API that controls the cache manager and a ConfigurationBuilder API that configures embedded caches.
Prerequisites
-
Add the
infinispan-coreartifact as a dependency in yourpom.xml.
Procedure
- Initialize the default cache manager so you can add embedded caches.
-
Add at least one embedded cache with the
ConfigurationBuilderAPI. -
Invoke the
getOrCreateCache()method that either creates embedded caches on all nodes in the cluster or returns caches that already exist.
// Set up a clustered cache manager.
GlobalConfigurationBuilder global = GlobalConfigurationBuilder.defaultClusteredBuilder();
// Initialize the default cache manager.
DefaultCacheManager cacheManager = new DefaultCacheManager(global.build());
// Create a distributed cache with synchronous replication.
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.clustering().cacheMode(CacheMode.DIST_SYNC);
// Obtain a volatile cache.
Cache<String, String> cache = cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).getOrCreateCache("myCache", builder.build());