You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Spring Boot实现本地缓存并与云端Redis中心缓存同步

开源方案选型

完全不需要付费的Redis Pro,开源生态有成熟的两级缓存(本地缓存+中心Redis)实现方案,以下是两种生产级可用的选型:

  • 基础组合方案:Caffeine本地缓存 + Spring Cache抽象 + Redis社区版
    是Spring生态最通用的实现,无额外第三方依赖侵入,灵活度高,所有组件完全开源免费
  • 开箱即用方案:JetCache
    阿里开源的缓存框架,原生支持两级缓存自动同步、缓存穿透/击穿防护、跨节点一致性通知,无需手动实现同步逻辑,兼容Spring Boot注解体系
Spring Boot 配置实现步骤

方案1:Spring Cache + Caffeine + Redis 手动实现

1. 引入核心依赖

<dependencies>
  <!-- Spring Cache抽象层 -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
  </dependency>
  <!-- Redis客户端 -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>
  <!-- 高性能本地缓存Caffeine -->
  <dependency>
    <groupId>com.github.benmanes.caffeine</groupId>
    <artifactId>caffeine</artifactId>
  </dependency>
</dependencies>

2. 配置GCP Redis连接

在application.yml中配置你在谷歌云平台上创建的Redis实例参数:

spring:
  redis:
    host: 你的GCP Redis内网地址
    port: 6379
    password: 你的Redis实例密码
    timeout: 3000ms

3. 实现跨节点缓存同步逻辑

用Redis自带的发布订阅能力实现本地缓存变更通知:

  1. 定义缓存变更事件的Topic,所有节点启动时订阅该Topic
  2. 当任意节点执行缓存更新/删除操作时,先更新/删除本地缓存和中心Redis缓存,再向Topic发送缓存Key失效通知
  3. 其他节点收到通知后,删除本地对应Key的缓存,保证所有节点本地缓存与中心缓存一致

参考核心配置代码:

// 缓存消息监听器
@Component
public class CacheSyncMessageListener implements MessageListener {
    @Autowired
    private CacheManager caffeineCacheManager;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String invalidKey = new String(message.getBody());
        Cache cache = caffeineCacheManager.getCache("yourCacheName");
        if (cache != null) {
            cache.evict(invalidKey);
        }
    }
}

方案2:JetCache 开箱即用实现

1. 引入依赖

<dependency>
  <groupId>com.alicp.jetcache</groupId>
  <artifactId>jetcache-starter-redis</artifactId>
  <version>2.7.3</version>
</dependency>

2. 基础配置

jetcache:
  statIntervalMinutes: 15
  areaInCacheName: false
  local:
    default:
      type: caffeine
      keyConvertor: fastjson
      defaultLimit: 1000 # 本地缓存最大Key数量
  remote:
    default:
      type: redis
      host: 你的GCP Redis地址
      port: 6379
      password: 你的Redis密码
      keyConvertor: fastjson
      valueEncoder: java
      valueDecoder: java
      poolConfig:
        minIdle: 2
        maxIdle: 10
        maxTotal: 50

3. 直接使用两级缓存

在需要缓存的方法上加注解即可自动实现本地+远程两级缓存,框架自动处理跨节点同步:

@Cached(name = "userCache:", key = "#userId", expire = 3600, localExpire = 60)
public User getUserById(Long userId) {
    // 你的业务查询逻辑
}
生产使用注意事项
  • 本地缓存仅适合存储访问频率高、更新频率低的小型数据,单Key大小建议控制在10KB以内
  • 对一致性要求高的场景可以适当缩短本地缓存过期时间(比如30-60秒),即使出现极短暂不一致也会快速自动对齐
  • 核心数据更新时建议执行双删策略:先删本地缓存,再删Redis缓存,间隔1秒后再删一次Redis缓存,避免缓存击穿问题

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:54:07