Skip to main content

dawdler-cache-jedis

Module Introduction​

Cache module implemented with jedis.

1. Add the dependency to pom​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-cache-jedis</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;// Note: the jedis implementation does not read this configuration; whether the redis cache is bounded is determined by the expiration time, see the notes below
}

@Override
public Duration getExpireAfterAccessDuration() {
return Duration.ofSeconds(30);
}

@Override
public Duration getExpireAfterWriteDuration() {
return null;
}

@Override
public String getFileName() {
return "jedis";
}

}

@ResponseBody
@RequestMapping(value = "/info/{userId}", method = RequestMethod.GET)
@Cacheable(cacheManager = "jedis", 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: At least one of getExpireAfterWriteDuration and getExpireAfterAccessDuration must be configured; otherwise an exception is thrown at startup (redis has no maximumSize fallback, and a cache that never expires will make redis memory grow continuously).

Note: When both expiry times are configured (dual TTL), the two windows are timed independently and whichever expires first wins (semantics aligned with native caffeine): on write it starts with the smaller of the two durations (a write is regarded as an access), read renewal is min(expireAfterAccess, remaining write window), and once the write window is exhausted there is no further renewal, so even hot keys will necessarily expire within expireAfterWrite after being written and will not live forever due to continuous access. For dual TTL, each write and read is executed atomically by a single Lua script (the value carries an internal timestamp header, and the timestamp uses the redis server-side TIME to avoid clock skew across nodes). Existing entries written with the old encoding (no header) before the upgrade can still be read normally but are not renewed, and they naturally expire with the TTL. When only expireAfterAccess is configured, read renewal has no upper limit (refresh-only semantics, hot keys never expire, use with caution).

Note: getMaxSize() has no effect in this implementation (jedis), because redis has no per-cache-name capacity limit capability. Whether the cache is bounded is entirely determined by the expiration time. All keys written within the TTL window coexist in redis (peak key count ≈ write rate × TTL). Capacity control recommendations:

  1. Constrain the TTL value with the formula write rate × TTL × average value size < redis maxmemory;
  2. Configure maxmemory on the redis server; the eviction policy is recommended to be volatile-lfu (only evict keys with a TTL; under the noeviction policy, a put throws an OOM exception once full, and allkeys-* policies would mistakenly evict keys of other businesses on the same instance);
  3. When the key cardinality is large and there are hotspots, add a caffeine cache layer in front to intercept requests before writing back to the origin.

Note: When getExpireAfterAccessDuration is configured, reads use the redis 6.2+ GETEX command, atomically renewing the expiry while fetching the value in a single network round trip (the old implementation used two serial round trips, GET + PEXPIRE), requiring redis server version 6.2 or later. When a separate TTL for the negative cache is also configured (getNullValueExpireAfterWriteDuration), reads switch to a Lua script (a single script atomically completes the fetch + renewal only for real values; null entries are not renewed on read, because renewal would only extend the window in which "data does not exist" is misjudged, aligning with the caffeine implementation semantics), requiring redis to support EVAL (2.6+). With dual TTL (configured together with getExpireAfterWriteDuration), reads use a Lua script (a single script atomically fetches the value + renews capped by the write window, also renewing only real values), requiring redis to support EVAL (2.6+).

Note: Cache keys are encoded as cacheName:typeSimpleName#dataKey; the cache name and the data key are each escaped (:, and the glob metacharacters *?[]{}, are prefixed with \, and \ is escaped as \\), and the data key also carries a type simple name prefix separated by # (e.g., Integer#1 and String#1 are different entries, preventing keys with the same literal but different types from sharing a slot and reading a value of the wrong type). Load locks occupy an independent load-lock: namespace, so that different caches whose names contain : or glob metacharacters (e.g., user and user:detail, user[1] and user1) do not have conflicting keys and clear will not mistakenly delete each other's entries, and a legitimate entry whose data key is named load-lock:xxx does not interfere with load locks. Existing entries written with the old encoding (no type prefix) before the upgrade cannot be hit after the upgrade and are not cleaned up by clear; they naturally expire with the TTL. clear is executed in batches using SCAN + UNLINK, is not atomic, and concurrent readers may see a partially cleared state.