Asynchronous Cache Update With Spring Cache Abstraction

£可爱£侵袭症+ 提交于 2019-12-03 13:51:17
Matteo

Perhaps you could try something like:

  1. Configure the cache:

    @Configuration
    @EnableCaching
    public class CacheConfig {
    
        @Bean
        public CacheManager cacheManager() {
            SimpleCacheManager simpleCacheManager = new SimpleCacheManager();
    
            GuavaCache chache= new GuavaCache("cacheKey", CacheBuilder.newBuilder().build());
    
            simpleCacheManager.setCaches(Arrays.asList(cacheKey));
    
            return simpleCacheManager;
        }
    }
    
  2. Read the value to be cached suppose a String(I use a @Service as example)

    @Service
    public class MyService{
    
        @Cacheable("cacheKey")
        public String getStringCache() {
            return doSomething();
        }
    
        @CachePut("cacheKey")
        public String refreshStringCache() {
            return doSomething();
        }
        ...
    }
    

    Both getStringCache() and refreshStringCache() invoke the same function in order to retreive the value to be cached. The controller invoke only getStringCache().

  3. Refresh the cache with a scheduled tasks doc

    @Configuration
    @EnableScheduling
    public class ScheduledTasks {
    
        @Autowired
        private MyService myService;
    
        @Scheduled(fixedDelay = 30000)
        public void IaaSStatusRefresh(){
            myService.refreshStringCache();
        }
    }
    

    In this way the scheduled task forces the cache refresh every 30s. Anyone who accessed to getStringCache() will find an updated data into the cache.

In one project using Spring Cache abstraction, I did the following things to reach the same goal, but still manages to hide the cache's actual vender, i.e., it should work with whatever cache provider Spring supports(currently Guava, but the application can switch to a clustered cache provider if required).

The core concept is to 'capture' cache usage patterns, and 'replay' those operations in another background threads, probably by a scheduler.

It needs to use reflection and some AOP programming for the 'capture' part if I want to keep the code non-intrusive, and luckily for Spring, Spring AOP provides all the toolsets I needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!