星期四, 一月 20, 2022

Spring Cache Concurrency Problems

没有评论

 

1. invoke and complete @CacheEvict during @Cacheable

Imagine that the @Cacheable method reads some data at time 1, and the data changed at time 2. The @CacheEvict method evicts the cache, and when time 4 the @Cacheable method completed, it will add the old data to the cache, and the next time @Cacheable method will use the cache that holds the old data.

1.1. solve the problem

Use a high priority aop that stores time 1 and time 3, and at time 4, if time 1 is less than time 3, evict the cache.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@Around("cacheableMethods(param)")
public Object aroundCache(ProceedingJoinPoint pjp, String param) throws Throwable {
    long beginTime = System.nanoTime();

    Object retVal = pjp.proceed();
    Long evictTime = cache.getIfPresent(param);
    if (evictTime != null && evictTime.compareTo(beginTime) > 0) {
        // remove Cache
        Boolean delete = redisTemplate.delete("note:test::" + param);
        log.info("deleted? {}", delete);
    }
    return retVal;
}

@After("cacheEvictMethods(param)")
public void afterEvict(String param) {
    cache.put(param, System.nanoTime());
}

没有评论 :

发表评论