Cache invalidation in Ehcache

后端 未结 5 1390
北恋
北恋 2020-12-19 09:03

I am using Ehcache in Hibernate.

How can I notify the cache that the database has changed? How can I invalidate the cached data? How can I programmatically achieve t

相关标签:
5条回答
  • 2020-12-19 09:39

    Try:

    CacheManager.create().clearAll()
    

    It will clear all caches in CacheManager.

    To clear only one particular cache, get it from cache manager and remove all elements:

    CacheManager cacheManager = CacheManager.create();
    Ehcache cache = cacheManager.getEhcache(cacheConfiguration.getName());
    cache.removeAll();    
    
    0 讨论(0)
  • 2020-12-19 09:41

    This is how you can invalidate all EhCache items without bothering what the individual cache names are:

    CacheManager manager = CacheManager.getInstance();
    
    String[] names = manager.getCacheNames();
    
    for (String name : names)
    {
        Cache cache = manager.getCache(name);
    
        cache.removeAll();
    }
    
    0 讨论(0)
  • 2020-12-19 09:50

    In case if you want to remove a specific cache (eg:employeeCache)

    @Autowired
    CacheManager cacheManager;
    

    place where you want to invalidate cache, use below code

        Cache cache = cacheManager.getCache("employeeCache");
        cache.removeAll();
    
    0 讨论(0)
  • 2020-12-19 09:53

    What do exactly mean? There are 2 ways to make a change in the database: inside the app & outside the app

    Inside the app you can trigger easily an invalidation. The second one is a harder to solve. Cache elements are stored with a key and based on that key you can delete it.

    CacheManager manager = CacheManager.getInstance();
    cache = manager.getCache(cacheName);
    cache.remove(key);
    
    or 
    
    cache.removeAll();
    

    Depending how you configured ehcache of course. But you need to know the name of the cache that holds the object.

    0 讨论(0)
  • 2020-12-19 09:56

    Set cache expiration so data is refreshed as or more often than the database changes .

    Also you can update in cache only elements that change in the database .

    0 讨论(0)
提交回复
热议问题