提到的咖啡因库提供了这个功能。你只需要提供你自己的 Expiry 实现。到期时间可能取决于键、值或您决定的任何内容,例如:
.expireAfter(new Expiry<CacheKey, CacheValue>() {
@Override
public long expireAfterCreate(@NonNull CacheKey key, @NonNull CacheValue value, long currentTime) {
return calculateBasedOnKey(key);
}
@Override
public long expireAfterUpdate(@NonNull CacheKey key, @NonNull CacheValue value, long currentTime, @NonNegative long currentDuration) {
return calculateBasedOnValue(value);
}
@Override
public long expireAfterRead(@NonNull CacheKey key, @NonNull Long CacheValue, long currentTime, @NonNegative long currentDuration) {
return currentDuration; //not modifying the expiration time
}