dawdler-cache-caffeine
Module Introduction
Cache module implemented with caffeine.
1. Add the dependency to pom
<groupId>club.dawdler</groupId>
<artifactId>dawdler-cache-caffeine</artifactId>
2. Use annotations on methods of web interfaces or service interfaces
Example:
/**
* Define a cache. Note that it must be defined in a package path scanned by the web or service side.
*/
public class CacheConfigImpl implements CacheConfig {
@Override
public String getName() {
return "userCache";
}
@Override
public Long getMaxSize() {
return 1024L;
}
@Override
public Duration getExpireAfterAccessDuration() {
return Duration.ofSeconds(30);
}
@Override
public Duration getExpireAfterWriteDuration() {
return null;
}
}
@ResponseBody
@RequestMapping(value = "/info/{userId}", method = RequestMethod.GET)
@Cacheable(cacheManager = "caffeine", cacheName = "userCache", key = "'userCache:'+userId", condition = "userId == 2", unless = "result.data == null")
public BaseResult<User> info(@PathVariable("userId") Integer userId, @RequestHeader("site") String site) {
return userService.selectByPrimaryKey(userId);
}
Note: By default, a null method result is also put into the cache (internally represented by a NullValue sentinel to prevent cache penetration). If you do not want null results to be cached, configure unless = "result == null".
Note: When getMaxSize() is null or not positive, the capacity is not limited (no maximumSize is set), and whether the cache is bounded is determined by the expiration time.
Note: By default, null result entries share the TTL with real values. You can configure a separate, shorter validity period for null entries via getNullValueExpireAfterWriteDuration() of CacheConfig (the "data does not exist" determination should expire faster). This implementation supports it through the caffeine variant expiry (Expiry); reads do not renew the expiry of null entries, and real value entries are unaffected.
Note: When both expiry times, getExpireAfterWriteDuration and getExpireAfterAccessDuration, are configured (dual TTL), the two windows are timed independently and whichever expires first wins (native caffeine semantics): on write it starts with the smaller of the two durations, read renewal is min(expireAfterAccess, remaining write window), and the entry expires once the write window is exhausted, so even hot keys will necessarily expire within expireAfterWrite after being written. When a separate TTL for null entries is configured (variant expiry path), this implementation supports the same dual TTL semantics via an internal wrapper (carrying a write timestamp), which is automatically restored when read through the Cache interface. The underlying caffeine cache is not exposed (the internal wrapper and NullValue sentinel forms are implementation details; reads always go through the Cache interface).