cache - Neethahiremath/Wiki GitHub Wiki
In memory cache:
add below dependency in pom file
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
add @EnableCaching to main method
@Configuration
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
add below cache manager code in configuration class
private Cache cache;
@Bean
public CacheManager cacheManager() {
return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}
@Bean
public EhCacheManagerFactoryBean cacheManagerFctry() {
net.sf.ehcache.config.Configuration configuration = new net.sf.ehcache.config.Configuration();
configuration.setName("cache");
net.sf.ehcache.CacheManager cacheManager = new net.sf.ehcache.CacheManager(configuration);
cacheManager.addCache(cache);
EhCacheManagerFactoryBean cacheMgrFactoryBean = new EhCacheManagerFactoryBean();
cacheMgrFactoryBean.setAcceptExisting(true);
cacheMgrFactoryBean.setCacheManagerName("cache");
return cacheMgrFactoryBean;
add @Cacheable and store in cache - say its in CacheService class
@Cacheable("cache")
public List<String> get() {
long start = System.currentTimeMillis();
List<String> res= find();
log.info("query: took {}",
System.currentTimeMillis() - start);
return res;
}
call CacheService.get() method and use the data.