How to use key in state in cacheable annotation

I am caching function results using the @cacheable annotation. I have 3 different caches, and the key for each of them is the user ID of the current user associated with the argument in the method. On a specific event, I want to evict all cache entries that have a key starting with this particular user ID. For example:

@Cacheable(value = "testCache1", key = "'abcdef'")

I want the cache cut annotation to be something like:

@CacheEvict(value = "getSimilarVendors", condition = "key.startsWith('abc')")

But when I try to implement this, it gives me an error:

Property or field 'key' cannot be found on object of type'org.springframework.cache.interceptor.CacheExpressionRootObject' - maybe not      public?

What is the correct way to implement this?

+4
source share
1 answer

- Spring (.. @Cacheable, @CacheEvict ..) 1 . @CacheEvict ( allEntries, ), () .

Spring Cache, evict (key: Object) . (, GemfireCache), , , (, , GemFire, Google Guava Cache, . .)

, . - .

, , , , ... , . , @CacheEvict "", , . , - SpEL ...

@CacheEvict(condition = "#key.startsWith('abc')")
public void someMethod(String key) {
  ...
}

. , , . , ...

@CacheEvict
public void someMethod(String keyPattern) {
  ...
}

, Guava , "" , GuavaCache.

public class CustomGuavaCache extends org.springframework.cache.guava.GuavaCache {

  protected boolean isMatch(String key, String pattern) {
    ...
  }

  protected boolean isPattern(String key) {
    ...
  }

  @Override
  public void evict(Object key) {
    if (key instanceof String && isPattern(key.toString()))) {
        Map<String, Object> entries = this.cache.asMap();
        Set<String> matchingKeys = new HashSet<>(entries.size());
        for (String actualKey : entries.keySet()) {
          if (isMatch(actualKey, key.toString()) {
            matchingKeys.add(actualKey);
          }
        }
        this.cache.invalidateAll(matchingKeys);
    }
    else {
      this.cache.invalidate(key);
    }
  }
}

GuavaCacheManager, "" GuavaCache (CustomGuavaCache)...

public class CustomGuavaCacheManager extends org.springframework.cache.guava.GuavaCacheManager {

  @Override
  protected Cache createGuavaCache(String name) {
    return new CustomGuavaCache(name, createNativeGuavaCache(name), isAllowNullValues());
  }
}

Guava invalidateAll (: ). , , Java Regex "" , isMatch(key, pattern).

, , ( - ) () , ( ; -)

, !

Cheers,

+5

Source: https://habr.com/ru/post/1606436/


All Articles