Skip to main content

dawdler-cache-core

Module Introduction​

The cache core module provides the annotations (Cacheable, CacheEvict, CachePut), the CacheManager cache manager and the CacheConfig cache configuration.

1. Adding the dependency in pom​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-cache-core</artifactId>

2. Annotations provided by the core module (Cacheable, CacheEvict, CachePut)​

1.1 Cacheable​

@Cacheable is used on methods of method components: if a cached value exists it is returned; otherwise the method is invoked, its result is put into the cache and then returned.

  1. If the input condition expression (condition) holds and a cached value is found, return it directly (a cached null is returned directly as null).

  2. If the input condition expression (condition) holds but no cached value is found, execute the method; if the method result matches the result expression (unless), put it into the cache and return the result, otherwise return the result directly.

  3. If the input condition expression (condition) does not hold, invoke the method directly without reading from or writing to the cache.

A method result of null is cached by default as well (represented internally by a NullValue sentinel to prevent cache penetration; configure unless = "result == null" if null results should not be cached).

Transaction semantics (the cache aspect sits outside the transaction aspect, fixed by @DeclarePrecedence):

  1. On a cache miss, proceed() enters the transaction aspect to execute. If the method has its own transaction, it has already committed before the return value is loaded and the cache write happens afterwards; when the method joins an outer transaction (nested call), the write is registered on the outer transaction's afterCommit and only happens after the outer commit, while a rollback means no cache write. In every scenario the cache write never happens before the transaction commits, so rolled-back data is never left in the cache. On a cache hit the transaction aspect is not entered, so a hit no longer pays the connection cost of opening and committing an empty transaction.

  2. For cache-stampede protection (single flight), the concurrency waiters share the loaded result at the moment the value actually becomes visible. If the method has its own transaction, the value is committed as soon as loading returns, so there is no uncommitted window; when only the loading method joins an outer transaction, publishing the single-flight result (de-registering and sharing the result) is deferred until the outer transaction reaches its final state - waiters share the result only after the commit and the cache write landed, and on rollback/write failure waiters are woken immediately to reload. New requests for the same key that arrive during the commit window still join the same flight and wait instead of each recomputing the business logic (stampede protection does not lapse inside the transaction window). The wait limit is still the single-flight wait limit (waitMillis); when a transaction does not commit for a long time, waiters time out and fall back to loading directly.

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Cacheable {

/**
* Specifies the cacheManager, e.g. caffeine or jedis
*/
String cacheManager();

/**
* The name of the cache
*/
String cacheName();

/**
* The cache key; supports JEXL expressions, with method parameter names as the built-in variables
*/
String key() default "";

/**
* Input condition expression executed before the call; supports JEXL expressions and must evaluate to true or false, with method parameter names as the built-in variables.
* The cache is used (read and write) only when the input satisfies the condition; otherwise the method is invoked directly
*/
String condition() default "";

/**
* Condition expression on the method result; supports JEXL expressions and must evaluate to true or false, with result as the built-in variable (the key of the method execution result).
* The result is put into the cache only when it does NOT satisfy this condition. A null result is cached by default (represented by an internal sentinel to prevent cache penetration);
* configure result == null if null results should not be cached
*/
String unless() default "";

}

1.2 CacheEvict​

@CacheEvict is used to remove cache entries.

When the annotation's cacheManager is not specified (defaults to empty), the only cacheManager registered in the current scope is used; when several cacheManagers are registered, it must be specified explicitly (the same rule applies to @CachePut and to @Cacheable when an empty string is passed explicitly).

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CacheEvict {

/**
* The cache key; supports JEXL expressions, with method parameter names as the built-in variables
*/
String key() default "";

/**
* The array of cache names
*/
String[] cacheNames();

/**
* Specifies the cacheManager, e.g. caffeine or jedis
* When empty (the default) the only cacheManager registered in the current scope is used; when several are registered it must be specified explicitly
*/
String cacheManager() default "";

/**
* Input condition expression; supports JEXL expressions and must evaluate to true or false, with method parameter names as the built-in variables.
* The cache is evicted only when the input satisfies the condition
*/
String condition() default "";

/**
* Whether to clear the whole cache
*/
boolean allEntries() default false;

/**
* Whether to evict before the method executes
*/
boolean beforeInvocation() default false;

}

1.3 CachePut​

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CachePut {

/**
* The cache key; supports JEXL expressions, with method parameter names as the built-in variables
*/
String key();

/**
* The name of the cache
*/
String cacheName();

/**
* Specifies the cacheManager, e.g. caffeine or jedis
* When empty (the default) the only cacheManager registered in the current scope is used; when several are registered it must be specified explicitly
*/
String cacheManager() default "";

/**
* Input condition expression; supports JEXL expressions and must evaluate to true or false, with method parameter names as the built-in variables.
* The result is put into the cache only when the input satisfies the condition
*/
String condition() default "";

/**
* Condition expression on the method result; supports JEXL expressions and must evaluate to true or false, with result as the built-in variable (the key of the method execution result).
* The result is put into the cache only when it does NOT satisfy this condition. A null result is cached by default (represented by an internal sentinel to prevent cache penetration);
* configure result == null if null results should not be cached
*/
String unless() default "";

}

3. The CacheConfig cache configuration interface​

The interface used to configure a cache. An implementation must be defined on the web side or the service side (web components need to be loaded; the server side needs it on the scan path).


public interface CacheConfig {

/**
* Cache name
*/
String getName();

/**
* Maximum number of entries
* A positive value and at least one TTL (cache time to live / expire-after-access) must be configured - one of the two - otherwise AbstractCacheManager.createCache
* throws IllegalArgumentException (cache entries with neither a capacity limit nor an expiration only go in, never out, and leak unbounded memory).
* null or a non-positive value means no capacity limit (whether it takes effect depends on the implementation: with caffeine a positive value becomes maximumSize,
* while the jedis implementation ignores this setting - redis has no capacity limit isolated per cache name, so whether the cache is bounded depends on the TTL,
* and therefore the jedis implementation still throws when only this item is configured without a TTL)
*/
Long getMaxSize();

/**
* Expire after access (read renewal duration)
* When configured together with the cache TTL (write window), each window is timed on its own and whichever comes first expires (semantics aligned with caffeine's native dual TTL):
* a write counts as one access, so after a write an entry starts from the smaller of the two durations; a read renews for min(this duration, remaining write window),
* entries whose write window is exhausted are no longer renewed and expire naturally with the remaining TTL - even a hot key inevitably expires within expireAfterWrite after being written.
* When only this duration is configured, read renewal is unlimited (refresh-only semantics: entries are kept as long as they keep being accessed)
*/
Duration getExpireAfterAccessDuration();

/**
* Cache TTL (write window duration: counted from the write/update, expiring whether or not the entry is accessed)
* For how it combines with expire-after-access see its comment (whichever comes first expires; the write window caps renewal).
* Recommendation: always configure this item for data with a limited lifetime or where the maximum staleness must be bounded
*/
Duration getExpireAfterWriteDuration();

/**
* Independent TTL for negative caching: NullValue sentinel entries written when the method result is null expire after this duration, while real-value entries are unaffected.
* The "data does not exist" determination should usually expire faster, so it is recommended to set a shorter value than the cache TTL;
* null or a non-positive value disables it, and null entries share the TTL with real values.
* When enabled, null entries are not renewed on read - renewing would only extend the window of a wrong "data does not exist" judgement, so they expire naturally with the TTL set at write time
* (the caffeine implementation supports this via variant expiration, while the jedis implementation writes null entries with an independent PX and, when expire-after-access is configured,
* renews only real values via a Lua script on read, giving the two implementations identical semantics)
*/
default Duration getNullValueExpireAfterWriteDuration() {
return null;
}

/**
* Serialization type, KRYO by default
*/
default SerializeType getSerializeType() {
return SerializeType.KRYO;
}

/**
* The name of the bound cacheManager, symmetric with the cacheManager() selector at the annotation level
* null or an empty string means broadcast: this configuration is injected into every CacheManager on the classpath (the default behavior in single-backend scenarios);
* a non-empty value means exact matching: it is injected only into the CacheManager whose cacheManagerName() equals this value.
* When several backends coexist, a configuration targeting a specific backend must set this - otherwise it is broadcast to incompatible backends,
* e.g. a configuration with maxSize but no TTL is valid for caffeine but makes the jedis implementation throw during construction, failing the whole deploy injection phase
*/
default String cacheManagerName() {
return null;
}

/**
* Configuration file name (needed e.g. when using dawdler-cache-jedis to configure redis)
*/
default String getFileName() {
return null;
}

/**
* Single-flight wait limit for stampede protection (the JVM-level wait and distributed polling share the same budget), overriding the global default (10s,
* -Ddawdler.cache.singleflight.waitMillis); after the wait times out the caller falls back to a double-check and then loads directly.
* Should be set to a value covering typical load time; null or a non-positive value uses the global default
*/
default Duration getSingleFlightWaitDuration() {
return null;
}

/**
* TTL of the distributed load lock (not used by in-JVM caches), overriding the global default (30s, -Ddawdler.cache.singleflight.loadLockTtlMillis);
* should exceed the single-flight wait limit plus the expected load time (otherwise a load slower than the wait limit lets waiters bypass the protection and load directly). null or a non-positive value uses the global default
*/
default Duration getLoadLockTtlDuration() {
return null;
}

}

4. Combined expiration semantics​

Configuration combinationSemantics
expireAfterWrite onlyEntries expire a fixed duration after write/update; reads do not renew
expireAfterAccess onlyReads renew with no limit - entries are kept as long as they keep being accessed (hot keys never expire; use with care)
Both configured (dual TTL)Each window is timed on its own and whichever comes first expires: after a write an entry starts from the smaller of the two durations (a write counts as an access), a read renews for min(expireAfterAccess, remaining write window), and once the write window is exhausted there is no renewal - even a hot key inevitably expires within expireAfterWrite after being written. Suitable for "frequently accessed entries may be kept, but no data may be staler than expireAfterWrite"

Additional notes for the redis (jedis) implementation:

  1. With dual TTL, each write and each read is one atomically executed Lua script (a write stores the value with an 18-byte internal header: 4-byte magic number + 13-digit write millisecond timestamp + 1-bit entry type; a read fetches the value and renews it atomically). The write timestamp comes from the redis server-side TIME (the same source as renewal, avoiding clock skew across nodes). Dual-TTL entries persisted with the old encoding (no header) before the upgrade can still be read normally (without renewal) and expire naturally with the TTL.
  2. When only expireAfterAccess is configured, reads use the redis 6.2+ GETEX command, fetching the value and renewing it atomically; dual-TTL reads go through a Lua script, which likewise requires the redis server to support EVAL (2.6+).

5. Cache failure policy​

A cache backend failure does not affect business call results: every cache read/write/evict exception in the annotation interception and the stampede-protected loading orchestration is handled uniformly by the global policy held in CacheErrorPolicies; the default LoggingCacheErrorPolicy only logs (semantics aligned with spring cache's CacheErrorHandler, extended with read degradation).

  • Read failure: log a WARN and degrade to a miss, falling back to executing the business method directly (loading).
  • Write failure (@Cacheable load write and @CachePut): log a WARN without rethrowing - by the time the cache is written the database operation has completed, and rethrowing would make the caller misjudge a business failure; on the transaction afterCommit path, a conditional eviction of the old value is additionally performed as a fallback (the value is read back first and deleted only if it is confirmed to be the value written by this node; if it cannot be read or has already been overwritten by another node the eviction is abandoned and only a log is written) so a stale value does not survive until the TTL.
  • Evict failure (@CacheEvict): log a WARN without rethrowing, and do not block execution of the business method.
  • Fallback direct load (the fallback path for wait timeout / load failure / reentrancy / load-lock channel failure) returns the business result without writing it back to the cache: a fallback caller does not hold the load right, and an unprotected write would overwrite the fresh value just written by a fast loader with an old snapshot. Not writing back only costs this request a subsequent cache miss; the next normal loading path that arrives fills it in.

It is recommended to replace the global policy at application startup via CacheErrorPolicies.setPolicy (e.g. to hook in alerting). Throwing an exception from handleGetError means strict mode (cache read failures propagate to the caller); handlePutError/handleEvictError/handleClearError should not throw per their contract (write/delete failures do not block the business).

The default LoggingCacheErrorPolicy limits its WARN logs by the combination of operation|cache name|exception type: within the interval window only the first log of a combination is emitted and suppressed counts are accumulated (the next log carries suppressed N). The limiter state is bounded (1024 entries, evicting the oldest key in insertion order), so an out-of-control number of cache names cannot cause memory exhaustion. The window is adjusted via a JVM startup parameter; configuring it as a non-positive value disables the limiter and emits every log:

PropertyDefaultDescription
dawdler.cache.error.log.intervalMillis10000Minimum output interval (ms) for WARN logs of the same error class; 0 or a negative value disables the limiter
-Ddawdler.cache.error.log.intervalMillis=30000
CacheErrorPolicies.setPolicy(new LoggingCacheErrorPolicy() {
@Override
public void handleGetError(Cache cache, Object key, Exception ex) {
// Hook in alerting or metrics, and return normally to degrade as a miss; throw an exception to propagate it to the caller (strict mode)
}
});

6. Extending the cache module​

Two implementations are currently provided: caffeine and jedis. To extend with another cache component, follow these steps.

  1. Create a project and a class extending the AbstractCacheManager abstract class, implementing the abstract method createCacheNative.

  2. Configure the concrete implementation of club.dawdler.cache.CacheManager via SPI.

See CaffeineCacheManager or JedisCacheManager for concrete implementations.

7. Scope of use​

Suitable for using cache annotations on the controller layer and the service layer.