/java-skills:caffeine-patternsfrom java-skills
Caffeine JVM 本地缓存技能:覆盖本地 vs Redis 选择决策、expireAfterWrite/expireAfterAccess/refreshAfterWrite 策略组合、CacheLoader 异步刷新、Spring Cache 集成及常见 LLM 错误纠正。
Ships in java-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
来源:https://github.com/ben-manes/caffeine/wiki
GitHub:https://github.com/ben-manes/caffeine
| 策略 | 行为 | 适用场景 |
|---|---|---|
| expireAfterWrite | 写入后固定时间过期 | ✅ 推荐(大多数业务),可预测的数据刷新 |
| expireAfterAccess | 最后访问后固定时间过期 | 会话缓存/用户登录状态 |
| refreshAfterWrite | 写后固定时间异步刷新(返回旧值) | 热点数据免阻塞刷新 |
| expireAfterWrite + refreshAfterWrite | 刷新在过期前执行,永不阻塞 | ⭐ 推荐组合 |
⚠️
refreshAfterWrite必须 <expireAfterWrite,否则刷新永远不触发
| # | 错误 | 正确做法 |
|---|---|---|
| 1 | ConcurrentHashMap<String, Object> + 手动过期 | Caffeine CacheBuilder 窗口 TinyLFU 算法 |
| 2 | 所有缓存都走 Redis | 单服务高频缓存走 Caffeine(纳秒级,Redis 毫秒级) |
| 3 | 不设置 maximumSize | maximumSize(10000) 防止内存溢出 |
| 4 | refreshAfterWrite 设置后不处理加载异常 | 旧值仍可用,加载失败不影响服务 |
| 5 | refreshAfterWrite > expireAfterWrite | 永远不刷新(过期就直接删除了) |
| 6 | CacheLoader.load() 返回 null | 返回 null = 缓存穿透(每次查都走 load) |
| 7 | 只设置 refreshAfterWrite 不设 maximumSize | 无界缓存 → OOM |
| 8 | 修改缓存返回的对象 | 缓存对象被外部修改 → 数据不一致 |
// ✅ expireAfterWrite + refreshAfterWrite 组合(推荐)
Cache<String, User> cache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(5, TimeUnit.MINUTES) // 5分钟过期
.refreshAfterWrite(3, TimeUnit.MINUTES) // 3分钟后台刷新(返回旧值)
.recordStats() // 记录命中率
.build(key -> loadFromDB(key)); // CacheLoader
LoadingCache<String, User> cache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.refreshAfterWrite(3, TimeUnit.MINUTES)
.build(new CacheLoader<String, User>() {
@Override
public @Nullable User load(String key) {
// 缓存未命中时加载
User user = userMapper.selectById(Long.parseLong(key));
// ✅ 不要返回 null!使用 Optional 或空对象占位
return user != null ? user : NULL_USER;
}
@Override
public @Nullable User reload(String key, User oldValue) {
// ✅ 刷新时优雅降级:加载失败返回旧值
try {
return load(key);
} catch (Exception e) {
log.error("刷新缓存失败, key={}", key, e);
return oldValue; // ← 返回旧值,不影响服务
}
}
});
// 使用
User user = cache.get("user:1"); // 自动加载
@Configuration
@EnableCaching // ← 必须!
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager mgr = new CaffeineCacheManager();
mgr.setCaffeine(Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(10_000)
.recordStats());
return mgr;
}
}
@Service
public class UserService {
@Cacheable(value = "users", key = "#id", unless = "#result == null")
public User getUser(Long id) {
return userMapper.selectById(id);
}
@CacheEvict(value = "users", key = "#id")
public void updateUser(Long id, UserDTO dto) {
userMapper.updateById(dto.toEntity(id));
}
@CacheEvict(value = "users", allEntries = true) // 清空整个缓存
public void refreshAll() { }
}
AsyncCache<String, User> asyncCache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(5, TimeUnit.MINUTES)
.refreshAfterWrite(1, TimeUnit.MINUTES) // 异步刷新
.buildAsync(key -> loadFromDB(key));
// 异步获取
CompletableFuture<User> future = asyncCache.get("user:1");
future.thenAccept(user -> System.out.println(user));
Cache<String, User> cache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.recordStats() // 启用统计
.build();
// 手动写入
cache.put("user:1", user);
// 手动失效
cache.invalidate("user:1");
// 统计数据
CacheStats stats = cache.stats();
log.info("命中率: {}, 加载次数: {}, 驱逐次数: {}",
stats.hitRate(), stats.loadCount(), stats.evictionCount());
本技能不收集、存储或传输任何用户数据。
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Generated from the plugin's indexed repository (full-stack-skills/java-skills) — no native marketplace selected
npx claudepluginhub p/full-statck-skills-java-skills39 skills in this plugin
/commons-patternsApache Commons 最佳实践模式。从官方文档提炼,覆盖 Commons Lang3(StringUtils千面判空/isEmpty vs isBlank/Validate抛NullPointerException迁移)、Commons IO(IOUtils.toString大文件陷阱/FileUtils.lineIterator逐行读模式/FilenameUtils.normalize路径规范化)、Commons Collections4(CollectionUtils.union/intersection/subtract集合运算)。 纠正 LLM 误用:混淆 StringUtils.isBlank vs isEmpty、IOUtils.toString 读大文件OOM、不知道 LineIterator 逐行读模式、用 lang 而非 lang3 包名。/easy4j-deployeasy4j 组织标准发布流程与多分支 Maven 发布规范。适用于 io.github.easy4j 仓库(如 openclaw-java-sdk、okhttp3-extension 及其他 easy-4-java 组织组件)的以下场景:(1) SDK 三分支正式版发布(标准流程:创建 tag → 发布 Maven Central → bump SNAPSHOT,支持子智能体并行编排),(1b) xxx-spring-boot-starter 十分支发布(依赖 SDK 先转正式版 + tag + Central + bump),(2) 发布阿里云私有库 SNAPSHOT,(3) 三分支(feature/1.0.x JDK 8、feature/2.0.x JDK 17、feature/3.0.x JDK 21)源码同步,(4) 发布前 CVE 扫描与依赖升级(Jackson BOM 版本控制规则、JDK 依赖天花板),(5) 发布故障排查(409 冲突、Central 拒绝 SNAPSHOT 依赖、argLine 问题)。触发词:发布、上线、deploy、release、发版、发布正式版、同步分支、版本号升级。/easyexcel-fill