Configure Applications for JCache Spring Caching Provider
Spring 3.2 and later versions support JCache compliant caching providers. You can also use JCache caching backed by NCache if your Spring version supports JCache. Simply modify the configuration by following the detailed steps below and use Spring seamlessly with NCache JCache Spring Caching Provider.
Pre-Requisites
For NCache Client, minimum required Java version is 9.0.
Note
- To use Maven packages for NCache Professional Edition, change the
<artifactId>
as shown below:<artifactId>ncache-professional-client</artifactId>
. - Add
spring-context-support
dependency for configuring Spring Framework. - Add
spring-boot-starter-cache
dependency for configuring Spring Boot.
Add Maven Packages
The user needs to add the following Maven dependencies in their pom.xml
file while working with NCache integration with Spring.
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<artifactId>ncache-client</artifactId>
<version>5.2.0</version>
</dependency>
Defining Cache Configurations
Note
To enable caching in Spring application, add @EnableCaching annotation.
JCache is bootstrapped through the presence of javax.cache.spi.CachingProvider
, JSR-107 compliant caching library, which exists on the classpath.
If you have more than one provider of JCache in your .classpath, then the tags spring.cache.jcache.provider
and spring.cache.type
need to be explicitly added in the application.properties file.
spring.cache.jcache.provider=com.alachisoft.ncache.jsr107.spi.NCacheCachingProvider
spring.cache.type=jcache
Configure Caches
Note
To initialize multiple caches on application startup, provide spring.cache.cache-names
tag with comma separated cache names.
To configure your cache for JCache Spring application, if you want to initialize your cache at the application startup, then for that you need to add the spring.cache.cache-names
tag in the application.properties file. The cache name should be the same as configured in Web Manager.
spring.cache.cache-names=demoCache,booksCache
Also, the cache can be configured through the JCacheManagerCustomizer
class which initializes the cache at runtime with the desired configuration.
@Configuration
public class CacheConfiguration implements JCacheManagerCustomizer
{
@Override
public void customize(CacheManager cacheManager)
{
MutableConfiguration mutableConfiguration = new MutableConfiguration();
mutableConfiguration.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));
cacheManager.createCache("booksCache", mutableConfiguration);
}
}
Once you have enabled caching, the next step is to bind the caching behavior to the methods, to use NCache as Caching Provider for Spring. For that refer to section Configure Applications using Caching Declaration.
See Also
Configure Application for Generic Spring Caching Provider
NCache as Spring Data Cache