MCPInstall

caffeine-patterns

Caffeine JVM 本地缓存技能。覆盖本地缓存 vs 远程缓存(Redis)选择决策树、expireAfterWrite vs expireAfterAccess vs refreshAfterWrite 三种过期策略对比与组合规则(refresh expireAfterWrite导致永远不刷新、CacheLoader返回null导致缓存穿透。

Installs
79
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/full-stack-skills/java-skills --skill caffeine-patterns
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads caffeine-patterns automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Caffeine JVM 本地缓存

来源:https://github.com/ben-manes/caffeine/wiki
GitHub:https://github.com/ben-manes/caffeine

Capability Boundaries

✅ Strong Suits

  1. 本地 vs 远程选择 — 单服务高频数据用Caffeine,多服务共享用Redis
  2. 过期策略 — expireAfterWrite(写入后) vs expireAfterAccess(访问后) vs refreshAfterWrite(异步刷新)
  3. CacheLoader — 自动加载缺失数据 + reload 异步刷新 + 优雅降级(返回旧值)
  4. Spring Cache 集成 — @Cacheable/@CacheEvict + CaffeineCacheManager
  5. 驱逐策略 — maximumSize(数量)/maximumWeight(权重)/Window TinyLFU
  6. 记录统计 — recordStats() + CacheStats 监控命中率

❌ Out of Scope

  1. 分布式缓存/共享数据 → redis-redisson-patterns
  2. Redis + Caffeine 两级缓存 → redis-redisson-patterns(已覆盖)

过期策略选择决策

策略行为适用场景
expireAfterWrite写入后固定时间过期✅ 推荐(大多数业务),可预测的数据刷新
expireAfterAccess最后访问后固定时间过期会话缓存/用户登录状态
refreshAfterWrite写后固定时间异步刷新(返回旧值)热点数据免阻塞刷新
expireAfterWrite + refreshAfterWrite刷新在过期前执行,永不阻塞⭐ 推荐组合

⚠️ refreshAfterWrite 必须 < expireAfterWrite,否则刷新永远不触发

LLM最常犯的错误

#错误正确做法
1ConcurrentHashMap<String, Object> + 手动过期Caffeine CacheBuilder 窗口 TinyLFU 算法
2所有缓存都走 Redis单服务高频缓存走 Caffeine(纳秒级,Redis 毫秒级)
3不设置 maximumSizemaximumSize(10000) 防止内存溢出
4refreshAfterWrite 设置后不处理加载异常旧值仍可用,加载失败不影响服务
5refreshAfterWrite > expireAfterWrite永远不刷新(过期就直接删除了)
6CacheLoader.load() 返回 null返回 null = 缓存穿透(每次查都走 load)
7只设置 refreshAfterWrite 不设 maximumSize无界缓存 → OOM
8修改缓存返回的对象缓存对象被外部修改 → 数据不一致

核心模式

模式 1: Caffeine 常用配置(推荐组合)

// ✅ 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

模式 2: CacheLoader + reload 优雅降级

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");  // 自动加载

模式 3: Spring Cache 集成

@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() { }
}

模式 4: 异步加载(AsyncCache)

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));

模式 5: 手动缓存操作 + 统计

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());

Gotchas

  1. Caffeine 是进程内缓存 — 多实例部署每个实例有独立缓存,数据不一致
  2. expireAfterAccess 适合会话缓存 — 写入后频率很高就设置 access
  3. refreshAfterWrite 必须 < expireAfterWrite — 否则刷新没意义
  4. CacheLoader.load() 不能返回 null — 返回空占位对象或抛异常
  5. Spring Cache 的 @Cacheable 返回值必须可序列化 — 如果用 Redis 作为后端
  6. maximumSize 驱逐可能丢失数据 — 重要数据用数据库作为最终保障
  7. 与 Redisson 配合 — Caffeine(L1) + Redis(L2) 是经典的两级缓存组合
  8. 缓存对象可变时注意防御性拷贝 — 外部修改缓存对象导致数据不一致
  9. recordStats() 不影响性能 — 生产环境建议开启
  10. expireAfter(Expiry) 支持自定义过期时间 — 根据 value 动态决定 TTL
  11. Caffeine 3.x 与 2.x 兼容性 — Spring Boot 2.x 使用 Caffeine 2.x,Spring Boot 3.x 使用 3.x
  12. weakKeys/softValues 慎用 — GC 触发的驱逐不可预测

Data Privacy

本技能不收集、存储或传输任何用户数据。

FAQ

What does the caffeine-patterns skill do?

Caffeine JVM 本地缓存技能。覆盖本地缓存 vs 远程缓存(Redis)选择决策树、expireAfterWrite vs expireAfterAccess vs refreshAfterWrite 三种过期策略对比与组合规则(refresh expireAfterWrite导致永远不刷新、CacheLoader返回null导致缓存穿透。

How do I install caffeine-patterns?

Run npx skills add https://github.com/full-stack-skills/java-skills --skill caffeine-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/caffeine-patterns/ (personal) or .claude/skills/caffeine-patterns/ (project).

Which AI agents can use caffeine-patterns?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is caffeine-patterns safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains caffeine-patterns?

It is published by full-stack-skills in full-stack-skills/java-skills. It has 79 recorded installs.

More from full-stack-skills/java-skills

View all →

java-development-manual

full-stack-skills/java-skills

Java开发手册规约集合,基于阿里巴巴Java开发手册(嵩山版)。 涵盖7大维度:编程规约、异常日志、单元测试、安全规约、MySQL数据库、工程结构、设计规约。 当用户需要:(1) 编写或审查Java代码 (2) 检查命名/代码规范 (3) 处理异常和日志 (4) 编写单元测试 (5) 安全编码 (6) 数据库设计 (7) 工程架构设计时使用此skill。 触发词:Java规范、阿里规约、代码规范、开发手册、编程规约、异常处理、单元测试、安全、MySQL、工程结构、设计模式。

Backend & APIs119 installs

mybatis-plus-patterns

full-stack-skills/java-skills

Open the skill to read its SKILL.md instructions.

Backend & APIs114 installs

java-code-comments

full-stack-skills/java-skills

Provides comprehensive guidance for adding Java code comments following industry standards and best practices. This skill helps add class-level comments, method-level comments, and field-level comments to Java code. Use when the user wants to add comments to Java code, needs to document Java classes/methods/fields, wants to improve code documentation, or needs to generate JavaDoc comments. This skill covers Controller, Service, ServiceImpl, Mapper, Model, Entity, BO (Business Object), DTO, VO, and other common Java component types. The skill follows a systematic workflow: scan codebase, identify components, create todo list, and add comments in order (class comments → method comments → field comments).

Backend & APIs112 installs

java-conventions

full-stack-skills/java-skills

统一 Java 项目编码规范与注释规范(SLF4J+Lombok 日志、Bean Lombok 注解选择、判空 Objects/Optional、工具类优先级 Spring→Apache Commons→Hutool→Guava、复杂逻辑用设计模式/简单逻辑不拆分、Controller/Service/ServiceImpl/Mapper 注释一致性)。当需要“按 Java 规范重构/Review/补全注释/统一日志/统一工具类使用/补全 JavaDoc”时使用。

Backend & APIs108 installs

mybatis-patterns

full-stack-skills/java-skills

Open the skill to read its SKILL.md instructions.

Backend & APIs102 installs

mapstruct-patterns

full-stack-skills/java-skills

MapStruct 最佳实践模式。从官方 Reference Guide 提炼,覆盖 Mapper 三种定义方式(接口/抽象类/default方法)、Spring 注入策略(CONSTRUCTOR推荐/SETTER解决循环依赖)、嵌套映射模式(显式子方法 dot notation 一次性配置)、@Qualifier @Named 的安全选择、Lombok 集成规则、@MappingComposition 谨慎使用。 纠正 LLM 最常见的错误:用反射 BeanUtils 而非编译期 MapStruct、嵌套映射全写在一个方法、不知 SETTER 解决循环依赖。

Backend & APIs97 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs