在 Java 中,API 接口缓存通常是为了减少重复计算、降低数据库/下游服务压力、提升响应速度。下面从常见缓存位置、实现方式、典型示例和注意事项几个方面系统说明。
Cache-Control、ETag、Last-ModifiedCache-Control: max-age=300
ETag: "abc123"
✅ 优:完全不请求服务器
❌ 缺:无法强制失效
如 Nginx / Spring Cloud Gateway
proxy_cache my_cache;
proxy_cache_valid 200 5m;
✅ 优:对业务代码无侵入
❌ 缺:缓存粒度较粗
Java 应用内部缓存接口返回结果
@SpringBootApplication
@EnableCaching
public class Application {}
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{id}")
@Cacheable(value = "user", key = "#id")
public User getUser(@PathVariable Long id) {
System.out.println("查询数据库");
return userService.findById(id);
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
spring:
cache:
type: caffeine
caffeine:
spec: maximumSize=1000,expireAfterWrite=5m
✅ 优点:简单、声明式
✅ 常见缓存:
@Cacheable(value = "user", key = "#id", cacheManager = "redisCacheManager")
public User getUser(Long id) {
return userMapper.selectById(id);
}
Redis 缓存结构示例:
user::1 -> User JSON
✅ 适合:
private Map<Long, User> cache = new ConcurrentHashMap<>();
public User getUser(Long id) {
return cache.computeIfAbsent(id, k -> userService.findById(k));
}
✅ 优点:完全可控
❌ 缺点:需自己处理过期、大小、并发
适合复杂缓存逻辑(如多参数、条件缓存)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiCache {
String key();
long ttl() default 300;
}
@CacheEvict(value = "user", key = "#id")
public void updateUser(Long id) {}
@CachePut(value = "user", key = "#user.id")
public User updateUser(User user) {}
| 场景 | 策略 |
|---|---|
| 查询接口 | 缓存结果 |
| 详情接口 | key = id |
| 列表接口 | key = 方法 + 参数 |
| 更新接口 | 删除缓存 |
| 高频读 | 本地缓存 |
| 分布式 | Redis |
@Cacheable(value = "user", unless = "#result == null")
synchronized (this) {}
expire = 300 + Random.nextInt(60)
| 场景 | 推荐 |
|---|---|
| 单体应用 | Spring Cache + Caffeine |
| 微服务 | Spring Cache + Redis |
| 高并发 | 本地 + Redis 二级缓存 |
Java API 接口缓存 = 选对缓存位置 + 合理 key 设计 + 失效策略 + 并发安全
如果你愿意,可以告诉我:
我可以给你一个完整可运行示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。