在 Java 里,“API 接口缓存”通常分 三层 来看,不同场景用不同方案。下面按「从简单到复杂」给你梳理。
适合:REST API、Service 层方法缓存
@EnableCaching
@SpringBootApplication
public class Application {}
@RestController
public class UserController {
@GetMapping("/user/{id}")
@Cacheable(value = "user", key = "#id")
public User getUser(@PathVariable Long id) {
// 模拟耗时代码
return userRepository.findById(id);
}
}
@CacheEvict(value = "user", key = "#id")
public void deleteUser(Long id) {}
✅ 优点:简单、无侵入
❌ 缺点:默认内存缓存,重启丢失
适合:高并发、短生命周期缓存
@Bean
public CacheManager cacheManager() {
CaffeineCacheManager manager = new CaffeineCacheManager();
manager.setCaffeine(Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.MINUTES)
.maximumSize(1000));
return manager;
}
适合:微服务、多实例部署
@Cacheable(value = "user", key = "#id", cacheManager = "redisCacheManager")
public User getUser(Long id) {}
Redis 配置:
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory factory) {
return RedisCacheManager.builder(factory)
.cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofMinutes(10)))
.build();
}
✅ 优点:
适合:前端调用、静态数据
response.setHeader("Cache-Control", "max-age=300");
或 Spring 注解:
@GetMapping("/config")
@ResponseCache(maxAge = 300)
public Config getConfig() {}
String key = "user:" + id;
User user = redisTemplate.opsForValue().get(key);
if (user == null) {
user = userService.findById(id);
redisTemplate.opsForValue().set(key, user, 10, TimeUnit.MINUTES);
}
expire = 10 + Random.nextInt(5)
| 场景 | 推荐 |
|---|---|
| 单体应用 | Caffeine |
| 微服务 | Redis |
| 只读接口 | HTTP 缓存 |
| 高并发 | Redis + 本地缓存 |
如果你愿意,可以告诉我:
我可以给你 完整可直接用的代码模板。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。