
redis-redisson-patterns
Redis + Redisson 缓存与分布式锁技能。覆盖缓存Key命名规范、过期时间设置原则、RedisTemplate序列化选择(JSON vs JDK vs String)、Redisson分布式锁三大模式(watchDog/tryLock 有leaseTime/无leaseTime 决策)、缓存穿透(布隆/空值缓存)/击穿(互斥锁)/雪崩(随机TTL)防护、Caffeine vs Redis选择决策。 纠正 LLM:不设过期时间、StringRedisTemplate和RedisTemplate混用、Redisson锁不 try-finally unlock、看门狗在指定 leaseTime 时不生效。
- Installs
- 100
- 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 redis-redisson-patterns- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads redis-redisson-patterns automatically when relevant.
- 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.
Redis + Redisson 缓存与分布式锁
来源:https://redisson.org/docs/
GitHub:https://github.com/redisson/redisson
Redis:https://redis.io/documentation
Capability Boundaries
✅ Strong Suits
- 缓存Key规范 — 格式
{业务名}:{类型}:{ID},统一前缀 - 过期时间原则 — 热点数据长TTL、非热点短TTL、永远不设-1
- 序列化选择 — JSON vs JDK vs String 三种方案对比与配置
- Redisson分布式锁 — tryLock/watchDog/leaseTime/可重入/公平锁/红锁
- 缓存三大问题防护 — 穿透(布隆/空值)/击穿(互斥锁)/雪崩(随机TTL)
- Caffeine vs Redis选择 — 什么时候用本地缓存什么时候用Redis
- RedisTemplate 正确配置 — 统一 Key/Value 序列化
❌ Out of Scope
- 消息队列/发布订阅 → kafka / RabbitMQ
- Spring Session 共享 → spring-security
- Jedis/Lettuce 客户端选择 → 本文档推荐 Lettuce(Spring Boot默认)
序列化选择决策
| 方案 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| StringRedisTemplate | 简单、可读 | 只能存 String,对象需手动序列化 | 纯字符串缓存 |
| RedisTemplate + Jackson2JsonRedisSerializer | 可读、跨语言 | 性能略低 | ✅ 推荐(适用于大部分场景) |
| RedisTemplate + JdkSerializationRedisSerializer | 默认(含类型信息) | 不可读、体积大、只限Java | ❌ 避免(默认就是它) |
| RedisTemplate + GenericJackson2JsonRedisSerializer | 含@class类型 | 冗余字段多 | 缓存复杂对象 |
LLM最常犯的错误
| # | 错误 | 正确做法 |
|---|---|---|
| 1 | 缓存不设过期时间(永久) | 必须设 TTL,防止内存溢出 |
| 2 | StringRedisTemplate 和 RedisTemplate 混用 | 统一用一个,推荐 RedisTemplate + JSON 序列化 |
| 3 | 缓存穿透(查不存在数据直接透到DB) | 空值缓存(Boolean.FALSE, TTL 5分钟) 或布隆过滤器 |
| 4 | Redis 做高频热点缓存(每次1000qps以上) | 加 Caffeine 本地缓存层(L1本地 + L2 Redis) |
| 5 | lock.lock() 不用 try-finally | 必须 finally { lock.unlock() } |
| 6 | 缓存Key没有命名规范 | 统一格式:saas:user:10001、saas:order:list |
| 7 | Redisson 指定 leaseTime 还期待看门狗续期 | 指定 leaseTime 看门狗不生效! |
| 8 | 缓存雪崩不处理(大量Key同时过期) | TTL 加随机值(±30%) |
| 9 | 热点Key缓存击穿 | 互斥锁或永不过期+异步更新 |
| 10 | 使用 RedisTemplate 默认 JDK 序列化 | 改为 JSON 序列化(可读、跨语言) |
核心模式
模式 1: RedisTemplate 统一配置(JSON序列化)
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// ✅ 推荐:Jackson2JsonRedisSerializer
Jackson2JsonRedisSerializer<Object> serializer =
new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(LazySerializationTypeValidator.getDefaultTyper(),
ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setKeySerializer(new StringRedisSerializer()); // Key: String
template.setValueSerializer(serializer); // Value: JSON
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}
模式 2: 缓存穿透防护(空值缓存)
public User getUser(Long id) {
String key = String.format("saas:user:%s", id);
User user = (User) redisTemplate.opsForValue().get(key);
// 空值标记,直接返回
if (user == NULL_PLACEHOLDER) return null;
// 缓存命中
if (user != null) return user;
// 查询DB
user = userMapper.selectById(id);
if (user == null) {
// ✅ 空值缓存(防穿透),TTL 5分钟
redisTemplate.opsForValue().set(key, NULL_PLACEHOLDER, 5, TimeUnit.MINUTES);
return null;
}
// ✅ 正常缓存,30分钟
redisTemplate.opsForValue().set(key, user, 30, TimeUnit.MINUTES);
return user;
}
模式 3: Redisson 分布式锁三大模式
模式A: tryLock + watchDog(推荐) — 有等待时间 + 自动续期
RLock lock = redissonClient.getLock("lock:order:" + orderId);
// ✅ 只指定 waitTime,不指定 leaseTime → watchDog 生效(默认30s续期)
if (lock.tryLock(10, TimeUnit.SECONDS)) { // 等10秒获取锁
try {
// 业务处理(可能超过30秒,watchDog自动续期)
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
模式B: tryLock + leaseTime — 硬超时(看门狗不生效)
RLock lock = redissonClient.getLock("lock:order:" + orderId);
// ⚠️ 指定了 leaseTime → watchDog 不生效
if (lock.tryLock(10, 30, TimeUnit.SECONDS)) {
try {
// 必须在30秒内完成,否则锁自动释放
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
模式C: lock() — 阻塞等待 + watchDog
RLock lock = redissonClient.getLock("lock:order:" + orderId);
lock.lock(); // 阻塞直到获取锁,watchDog 生效
try {
// 业务处理
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
模式 4: 缓存雪崩防护(随机TTL)
// 相同业务场景的缓存 TTL 加随机值,避免同时过期
int baseTtl = 3600; // 1小时
int randomTtl = baseTtl + new Random().nextInt(600); // +0~10分钟随机
redisTemplate.opsForValue().set(key, value, randomTtl, TimeUnit.SECONDS);
模式 5: 缓存Key规范
// 命名格式: {业务}:{领域}:{实体}:{唯一标识}
private static final String USER_CACHE_KEY = "saas:user:detail:%s";
private static final String ORDER_LIST_KEY = "saas:order:list:%s:%d"; // userId + page
private static final String CONFIG_KEY = "saas:config:global";
String key = String.format(USER_CACHE_KEY, userId);
Gotchas
- 缓存必须设过期时间 — 永不设TTL = 内存泄漏
- Redisson lock 必须 try-finally unlock — 否则死锁
- watchDog 看门狗自动续期 — 未指定 leaseTime 时默认30s,每10s续一次
- 指定了 leaseTime 看门狗不生效 — 需要自动续期就别指定 leaseTime
- Redis 集群不能用批量 mget(跨Slot) — 改为循环 get 或 hash tag 固定 Slot
- 缓存雪崩:同一时间大量Key同时过期 — TTL 加随机值(±30%)
- 缓存击穿:热点Key过期瞬间大量请求穿透 — 互斥锁或永不过期+异步更新
- Caffeine更适合单服务高频缓存 — Redis用于分布式共享,Caffeine用于本地加速
- isHeldByCurrentThread() 必须在 unlock 前检查 — 避免 IllegalMonitorStateException
- RedisTemplate 默认 JDK 序列化 — 改为 JSON 序列化(可读、跨语言)
- Lettuce(Spring Boot 默认) 比 Jedis 更推荐 — 异步、连接池、社区活跃
- 布隆过滤器(RedissonBloomFilter)用于防穿透 — 适用于 key 数量大、不要求100%精确
Data Privacy
本技能不收集、存储或传输任何用户数据。
FAQ
What does the redis-redisson-patterns skill do?
Redis + Redisson 缓存与分布式锁技能。覆盖缓存Key命名规范、过期时间设置原则、RedisTemplate序列化选择(JSON vs JDK vs String)、Redisson分布式锁三大模式(watchDog/tryLock 有leaseTime/无leaseTime 决策)、缓存穿透(布隆/空值缓存)/击穿(互斥锁)/雪崩(随机TTL)防护、Caffeine vs Redis选择决策。 纠正 LLM:不设过期时间、StringRedisTemplate和RedisTemplate混用、Redisson锁不 try-finally unlock、看门狗在指定 leaseTime 时不生效。
How do I install redis-redisson-patterns?
Run npx skills add https://github.com/full-stack-skills/java-skills --skill redis-redisson-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/redis-redisson-patterns/ (personal) or .claude/skills/redis-redisson-patterns/ (project).
Which AI agents can use redis-redisson-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 redis-redisson-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 redis-redisson-patterns?
It is published by full-stack-skills in full-stack-skills/java-skills. It has 100 recorded installs.
More from full-stack-skills/java-skills
java-development-manual
full-stack-skills/java-skills
Java开发手册规约集合,基于阿里巴巴Java开发手册(嵩山版)。 涵盖7大维度:编程规约、异常日志、单元测试、安全规约、MySQL数据库、工程结构、设计规约。 当用户需要:(1) 编写或审查Java代码 (2) 检查命名/代码规范 (3) 处理异常和日志 (4) 编写单元测试 (5) 安全编码 (6) 数据库设计 (7) 工程架构设计时使用此skill。 触发词:Java规范、阿里规约、代码规范、开发手册、编程规约、异常处理、单元测试、安全、MySQL、工程结构、设计模式。
mybatis-plus-patterns
full-stack-skills/java-skills
Open the skill to read its SKILL.md instructions.
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).
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”时使用。
mybatis-patterns
full-stack-skills/java-skills
Open the skill to read its SKILL.md instructions.
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 解决循环依赖。
Popular data & databases skills
supabase-postgres-best-practices
supabase/agent-skills
Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and scheduled jobs (pgcron, pgmq), vector/semantic search (pgvector), and restoring dumps (pgrestore) or importing data. Also load it when diagnosing slow queries, high CPU, timeouts, EXPLAIN plans, connection exhaustion, locking, bloat, or rows visible to the wrong user or tenant. This is not just a performance guide — schema, migration, security, and SQL authoring tasks need these rules too, even for a one-column change or a single query.
prisma-client-api
prisma/skills
Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".
prisma-database-setup
prisma/skills
Deprecated compatibility name for prisma-orm-setup. Use only when a user or existing integration explicitly invokes prisma-database-setup; otherwise select prisma-orm-setup.
prisma-cli
prisma/skills
Prisma ORM 7 CLI reference for existing Prisma 7 applications or explicitly selected Prisma 7 workflows. Covers prisma init, generate, migrate, db, dev, studio, and mcp. For setup, connection repair, or Prisma 8, use prisma-orm-setup; not the Prisma Platform CLI.
prisma-postgres
prisma/skills
Deprecated compatibility name for prisma-postgres-setup. Use only when a user or existing integration explicitly invokes prisma-postgres; otherwise select prisma-postgres-setup.
prisma-driver-adapter-implementation
prisma/skills
Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.