Chapter 3. Running in Embedded Mode
Embed the Data Grid library in your project for in-memory data storage.
3.1. Adding the EmbeddedCacheManager Bean
Add
infinispan-spring-boot-starter-embeddedto your project’s classpath to enable Embedded mode.This starter operates in Remote Client/Server mode with
infinispan-spring-boot-starter-remoteon the classpath by default.Use the Spring
@Autowiredannotation to include anEmbeddedCacheManagerbean in your Java configuration classes, as in the following example:private final EmbeddedCacheManager cacheManager; @Autowired public YourClassName(EmbeddedCacheManager cacheManager) { this.cacheManager = cacheManager; }You are now ready to use Data Grid in Embedded Mode. Here is a simple example:
cacheManager.getCache("testCache").put("testKey", "testValue"); System.out.println("Received value from cache: " + cacheManager.getCache("testCache").get("testKey"));
3.2. Cache Manager Configuration Beans
You can customize the cache manager with the following configuration beans:
-
InfinispanGlobalConfigurer -
InfinispanCacheConfigurer -
Configuration -
InfinispanConfigurationCustomizer InfinispanGlobalConfigurationCustomizerNoteYou can create one
InfinispanGlobalConfigurerbean only. However you can create multiple configurations with the other beans.
InfinispanCacheConfigurer Bean
@Bean
public InfinispanCacheConfigurer cacheConfigurer() {
return manager -> {
final Configuration ispnConfig = new ConfigurationBuilder()
.clustering()
.cacheMode(CacheMode.LOCAL)
.build();
manager.defineConfiguration("local-sync-config", ispnConfig);
};
}
Configuration Bean
Link the bean name to the cache that it configures, as follows:
@Bean(name = "small-cache")
public org.infinispan.configuration.cache.Configuration smallCache() {
return new ConfigurationBuilder()
.read(baseCache)
.memory().size(1000L)
.memory().evictionType(EvictionType.COUNT)
.build();
}
@Bean(name = "large-cache")
public org.infinispan.configuration.cache.Configuration largeCache() {
return new ConfigurationBuilder()
.read(baseCache)
.memory().size(2000L)
.build();
}Customizer Beans
@Bean
public InfinispanGlobalConfigurationCustomizer globalCustomizer() {
return builder -> builder.transport().clusterName(CLUSTER_NAME);
}
@Bean
public InfinispanConfigurationCustomizer configurationCustomizer() {
return builder -> builder.memory().evictionType(EvictionType.COUNT);
}
3.3. Enabling Spring Cache Support
Add the @EnableCaching annotation to your application to enable Spring Cache support.
When this starter detects the EmbeddedCacheManager bean, it instantiates a new SpringEmbeddedCacheManager, which provides an implementation of Spring Cache.