Schedule Spring cache eviction?

╄→гoц情女王★ 提交于 2020-01-22 14:57:05

问题


Is it possible to schedule spring cache eviction to everyday at midnight?

I've read Springs Cache Docs and found nothing about scheduled cache eviction.

I need to evict cache daily and recache it in case there were some changes outside my application.


回答1:


Try to use @Scheduled Example:

@Scheduled(fixedRate = ONE_DAY)
@CacheEvict(value = { CACHE_NAME })
public void clearCache() {      
}

You can also use cron expression with @Scheduled.




回答2:


If you use @Cacheable on methods with parameters, you should NEVER forget the allEntries=true annotation property on the @CacheEvict, otherwise your call will only evict the key parameter you give to the clearCache() method, which is nothing => you will not evict anything from the cache.




回答3:


Spring cache framework is event driven i.e. @Cacheable or @CacheEvict will be triggered only when respective methods are invoked.

However you can leverage the underlying cache provider (remember the Spring cache framework is just an abstraction and does not provide a cache solution by itself) to invalidate the cache by itself. For instance EhCache has a property viz. timeToLiveSeconds which dictates the time till the cache be active. But this won't re-populate the cache for you unless the @Cacheable annotated method is invoked.

So for cache eviction and re-population at particular time (say midnight as mentioned) consider implementing a background scheduled service in Spring which will trigger the cache eviction and re-population as desired. The expected behavior is not provided out-of-box.

Hope this helps.




回答4:


I know this question is old, but I found a better solution that worked for me. Maybe that will help others.

So, it is indeed possible to make a scheduled cache eviction. Here is what I did in my case.

Both annotations @Scheduled and @CacheEvict do not seem to work together. You must thus split apart the scheduling method and the cache eviction method. But since the whole mechanism is based on proxies, only external calls to public methods of your class will trigger the cache eviction. This because internal calls between to methods of the same class do not go through the Spring proxy.

I managed to fixed it the same way as Celebes (see comments), but with an improvement to avoid two components.

@Component
class MyClass
{

    @Autowired
    MyClass proxiedThis; // store your component inside its Spring proxy.

    // A cron expression to define every day at midnight
    @Scheduled(cron ="0 0 * * *")
    public void cacheEvictionScheduler()
    {
        proxiedThis.clearCache();
    }

    @CacheEvict(value = { CACHE_NAME })
    public void clearCache()
    {
        // intentionally left blank. Or add some trace info.
    }    
}


来源:https://stackoverflow.com/questions/42688020/schedule-spring-cache-eviction

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