Java – invalidate the @ cacheable entry through comments on the interface?

I'm using spring and @ cacheable annotations to cache some database entries I want to invalidate the full cache periodically

So: is it effective to put these comments on interface methods? Or must these annotations be placed on class methods (even if they have an empty method body)?

public interface MyRepository extends CrudRepository<MyEntity,Long> {
    @Override
    @Cacheable("cache")
    Airline findOne(long id);

    @CacheEvict(value = "cache",allEntries = true)
    @Scheduled(cron = "0 0 1 * * *")
    void removeAll();
}

If I have @ cacheable on the interface method and @ cacheevict in the service, the application will start successfully If I use the above code, it won't work But maybe I did it wrong?

Solution

It may work, but I recommend putting these comments on the implementation

This is more like a theoretical problem, but we can think about it this way: interface is a common contract, but caching is an implementation detail

Your interface can be implemented in many ways. For example, one day you can have an hsqldbrepository. Caching is meaningless because it already exists in memory

In the sidenote, I'll think carefully about why you need to "expel all"... Depending on how often it happens, it may make your cache useless - and it's usually a sign of designing deeper problems If you want to evict an entity after a period of time, consider configuring timetolive / timetoidle – this is well supported by most cache backend

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>