温馨提示×

温馨提示×

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

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

Java API接口如何缓存

发布时间:2026-07-17 03:03:28 来源:亿速云 阅读:100 作者:小樊 栏目:编程语言

在 Java 中,API 接口缓存通常是为了减少重复计算、降低数据库/下游服务压力、提升响应速度。下面从常见缓存位置、实现方式、典型示例和注意事项几个方面系统说明。


一、API 接口缓存的常见位置

1️⃣ 客户端缓存(浏览器 / APP)

  • HTTP 缓存头:Cache-ControlETagLast-Modified
  • 适合:静态或不常变的数据
Cache-Control: max-age=300
ETag: "abc123"

✅ 优:完全不请求服务器
❌ 缺:无法强制失效


2️⃣ 网关层缓存(推荐)

Nginx / Spring Cloud Gateway

proxy_cache my_cache;
proxy_cache_valid 200 5m;

✅ 优:对业务代码无侵入
❌ 缺:缓存粒度较粗


3️⃣ 应用层缓存(最常用 ✅)

Java 应用内部缓存接口返回结果


二、Java 应用层接口缓存实现方式

✅ 方式一:Spring Cache(最推荐)

1. 开启缓存

@SpringBootApplication
@EnableCaching
public class Application {}

2. 接口方法加缓存注解

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

3. 配置缓存实现(以 Caffeine 为例)

<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

✅ 优点:简单、声明式
✅ 常见缓存:

  • Caffeine(本地)
  • Redis(分布式)

✅ 方式二:Redis 缓存接口数据(分布式系统)

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

✅ 优点:完全可控
❌ 缺点:需自己处理过期、大小、并发


✅ 方式四:AOP + 注解(自定义缓存)

适合复杂缓存逻辑(如多参数、条件缓存)

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiCache {
    String key();
    long ttl() default 300;
}

三、缓存更新与失效策略

1️⃣ 失效方式

@CacheEvict(value = "user", key = "#id")
public void updateUser(Long id) {}

2️⃣ 更新方式

@CachePut(value = "user", key = "#user.id")
public User updateUser(User user) {}

四、接口缓存的典型策略

场景 策略
查询接口 缓存结果
详情接口 key = id
列表接口 key = 方法 + 参数
更新接口 删除缓存
高频读 本地缓存
分布式 Redis

五、常见坑 & 注意事项 ⚠️

1️⃣ 缓存穿透

  • 解决:缓存空值 / 布隆过滤器
@Cacheable(value = "user", unless = "#result == null")

2️⃣ 缓存击穿

  • 解决:加锁 / 分布式锁
synchronized (this) {}

3️⃣ 缓存雪崩

  • 解决:过期时间加随机值
expire = 300 + Random.nextInt(60)

4️⃣ 缓存一致性

  • 更新 DB → 删除缓存(不是更新缓存)

六、推荐组合方案 ✅

场景 推荐
单体应用 Spring Cache + Caffeine
微服务 Spring Cache + Redis
高并发 本地 + Redis 二级缓存

七、一句话总结

Java API 接口缓存 = 选对缓存位置 + 合理 key 设计 + 失效策略 + 并发安全

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

  • 是否 Spring Boot 项目
  • 是否 单体 / 微服务
  • 是否需要 Redis / 本地缓存

我可以给你一个完整可运行示例

向AI问一下细节

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

AI