Video in progress
What mistakes are there in this combination of `@CacheEvict` and `@CachePut`, and how do you fix them?
@Transactional
@CachePut(cacheNames = "product", key = "#result.id")
@CacheEvict(cacheNames = "productList", allEntries = true)
public Product update(long id, ProductForm form) {
Product p = repo.findById(id).orElseThrow();
p.apply(form);
return p;
}
The cache writes happen before the transaction commits, a managed JPA entity ends up in the cache, and allEntries = true scans and deletes the whole prefix in Redis, which is expensive on a big cache. You need to make the cache manager transaction-aware and cache DTOs.
📖 Answer
There are several subtle problems in this code.
- Ordering and the transaction: when one method has
@Transactionaland the cache annotations, two proxies/advisors run. By default the cache interceptor runs inside the transaction: the cache is updated, and then if the commit fails, the cache is left with a state that isn't in the DB. To update after the commit, makeRedisCacheManagertransactionAware()(aTransactionAwareCacheDecorator), which does the put/evict after the commit.
RedisCacheManager.builder(cf)
.cacheDefaults(config)
.transactionAware()
.build();
-
The entity inside
#result: the returnedProductis a managed JPA entity and may hold lazy collections. During serialization you get aLazyInitializationException, or the whole graph ends up in the cache. You should put a DTO in the cache, not an entity. -
allEntries = true: in Redis this means finding and deleting the keys by prefix. By default Spring Data Redis still usesKEYS; you can switch toSCANwithBatchStrategies.scan(n), and on a big cache you should:
RedisCacheWriter writer = RedisCacheWriter.nonLockingRedisCacheWriter(cf, BatchStrategies.scan(1000));
Clearing the whole list cache on every product update is expensive in itself. Sometimes it's better to keep the list caches on a short TTL and drop the evict entirely.
- Key types: with
@Cacheable(key = "#id")the key is along, and with@CachePut(key = "#result.id")it's aLong. In Redis both becomeproduct::42, so there's no problem here. But if the key expressions are written differently in different methods (for example, one#id, another#p.id + ''), it's worth writing an integration test to check that they match.
Sign up to mark studied questions and save your progress.