温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java API接口怎么缓存

发布时间:2026-10-02 12:49:07 来源:亿速云 阅读:97 作者:小樊 栏目:编程语言

在 Java 里,“API 接口缓存”通常分 三层 来看,不同场景用不同方案。下面按「从简单到复杂」给你梳理。


一、单机内存缓存(最常用)

1️⃣ 使用 Spring 自带缓存(推荐)

适合: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) {}

✅ 优点:简单、无侵入
❌ 缺点:默认内存缓存,重启丢失


2️⃣ 使用 Caffeine(高性能本地缓存)

适合:高并发、短生命周期缓存

@Bean
public CacheManager cacheManager() {
    CaffeineCacheManager manager = new CaffeineCacheManager();
    manager.setCaffeine(Caffeine.newBuilder()
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .maximumSize(1000));
    return manager;
}

二、分布式缓存(集群必选)

3️⃣ Redis 缓存 API 结果

适合:微服务、多实例部署

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

✅ 优点:

  • 多实例共享
  • 支持过期、淘汰策略

三、HTTP 层缓存(接口级)

4️⃣ 使用 HTTP 缓存头

适合:前端调用、静态数据

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 + 本地缓存

如果你愿意,可以告诉我:

  • ✅ 用的是 Spring Boot 还是普通 Java
  • ✅ 单机和集群
  • ✅ 缓存的是 接口返回 / DB 查询 / 计算逻辑

我可以给你 完整可直接用的代码模板。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手