Spring Caching Example

The Spring Framework provides support for transparently adding caching to an application. At its
core, the abstraction applies caching to methods, thus reducing the number of executions based on
the information available in the cache. The caching logic is applied transparently, without any
interference to the invoker. Spring Boot auto-configures the cache infrastructure as long as caching
support is enabled via the @EnableCaching annotation.

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class MathService {
@Cacheable("piDecimals")
public int computePiDecimal(int i) {
// ...
}
}

This example demonstrates the use of caching on a potentially costly operation. Before invoking
computePiDecimal, the abstraction looks for an entry in the piDecimals cache that matches the i
argument. If an entry is found, the content in the cache is immediately returned to the caller, and
the method is not invoked. Otherwise, the method is invoked, and the cache is updated before
returning the value.

Supported Cache Providers

The cache abstraction does not provide an actual store and relies on abstraction materialized by the
org.springframework.cache.Cache and org.springframework.cache.CacheManager interfaces.
If you have not defined a bean of type CacheManager or a CacheResolver named cacheResolver (see
CachingConfigurer), Spring Boot tries to detect the following providers (in the indicated order):
7. Redis
9. Simple

It is also possible to force a particular cache provider by setting the
configprop:spring.cache.type[] property. Use this property if you need to disable
caching altogether in certain environment (such as tests).

Use the spring-boot-starter-cache “Starter” to quickly add basic caching
dependencies. The starter brings in spring-context-support. If you add
dependencies manually, you must include spring-context-support in order to use
the JCache, EhCache 2.x, or Caffeine support.

If the CacheManager is auto-configured by Spring Boot, you can further tune its configuration before
it is fully initialized by exposing a bean that implements the CacheManagerCustomizer interface.

@Bean
public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {
return new CacheManagerCustomizer<ConcurrentMapCacheManager>() {
@Override
public void customize(ConcurrentMapCacheManager cacheManager) {
cacheManager.setAllowNullValues(false);
}
};
}



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation