Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : How to remove from Ecache?

This is how I'm caching data on GET request:

@Cacheable(value = "userCache", key = "T(de.hybris.platform.commercewebservicescommons.cache.CommerceCacheKeyGenerator).generateKey(true,true,'DTO',#currentPage,#pageSize,#sort,#fields)")
public UsersDTO getUsers(final int currentPage, final int pageSize, final String sort,
            final String fields)
{
        // Code......
}

How can I delete only 'DTO' from cache for other requests for example when I trigger DELETE Request I want to remove 'DTO' ? And can we do it via annotation ?

Right now I'm doing this but I think it's removing entire userCache

public void updateUserCache()
    {
        final Cache cache = cacheManager.getCache("userCache");
        final Ehcache ehCache = (Ehcache) cache.getNativeCache();
        ehCache.getKeys().forEach(key -> {
            cache.evict(key);
        });
    }
like image 890
Junaid Avatar asked Nov 17 '25 06:11

Junaid


1 Answers

try like below code:

@CacheEvict(value = "userCache", key="#userId")
public void updateUserCache()
    {
....
...
}

or u can do like this

   if (cache.isKeyInCache(userId))
    {
        cache.remove(key);
    }
like image 143
TheSprinter Avatar answered Nov 19 '25 20:11

TheSprinter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!