Spring Simple Cache
In this post, I am going to explain about spring cache.
Overview
- Spring provides support for add cache to our applications.
- It reduces the number of executions, database hits and rest calls.
- Spring Boot provides a wrapper on top of all famous cache mechanisms.
How to make cachable for a method
- Adding cache any service method by simple add
@Chable("cacheName")
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class MathService {
@Cacheable("square")
public int squareOfNumber(int i) {
// Write your logic
}
}
- If anyone calls squareOfNumber(...), before invoking that method it checks in the cache (square cache) if found the value it returns value from cache else it executes the method and put the return value in the cache and returns the value to the Invoker.
- It checks in the cache for each and every time of method invoke, but it checks in cache name square cache with a given id.
- First time of a method invoke with the unique value it executes method, from second time onwards with same input value it will not execute method simple return from the cache.
- Spring default uses ConcurrentHashMap as default cache if we do not provide any cache settings to spring.
- Spring supports so many cache mechanisms.
Spring Supported Caches
- Generic
- JCache
- EH Cache 2.x
- Hazelcast
- Infinispan
- Couchbase
- Redis
- Caffeine
- Simple
Configure Simple CacheManager
@Bean
@Primary
public CacheManager myCacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("getUsers")));
return cacheManager;
}