I will give you the easiest way to enable second level cache in Spring Boot
Before continue there are so many types of second level cahes are available
1 - JCache
2 - Ehcache
3 - Gvava Cache
4 - Hazelcast Cache
5 - Caffeine Cache
and many more. each and every cache has there own implementations.
But there is one good thing about Spring Boot, to enable second level cache. If you don’t want to use any of caches whatever i mentioned on top. then follow below steps and you can enable second level cache very easily -
Step 1 - add below dependency in pom.xml
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-cache</artifactId>
- </dependency>
Step 2 - create one config class and add below code
- import java.util.ArrayList;
- import java.util.List;
- import org.springframework.cache.Cache;
- import org.springframework.cache.CacheManager;
- import org.springframework.cache.annotation.EnableCaching;
- import org.springframework.cache.concurrent.ConcurrentMapCache;
- import org.springframework.cache.support.SimpleCacheManager;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.Configuration;
- @Configuration
- @EnableCaching
- public class CacheConfig {
- @Bean
- public CacheManager cacheManager() {
- SimpleCacheManager cacheManager = new SimpleCacheManager();
- List<Cache> cacheList = new ArrayList<Cache>();
- cacheList.add(new ConcurrentMapCache("cache1"));
- cacheList.add(new ConcurrentMapCache("cache2"));
- //so like that you can create as many as you want
- cacheManager.setCaches(cacheList);
- return cacheManager;
- }
- }
Step 3 - Use wherever you want
- @Override
- @Cacheable(value = "cache1")
- public List<SomeObject> someList() {
- return repository.findAll();
- }
that’s it and works perfectly.
if you want to some more proper way then watch below video that is about Cache
Thanks for reading :)