如何基于“Keyspace Notification”自动清理过期租户缓存?

解读

在国内 Spring Cloud 生产环境,多租户 SaaS 平台普遍采用 Redis 做二级缓存,以缓解数据库压力并支持横向扩容。
租户数据往往按“租户 ID + 业务 Key”拼接成缓存键,并设置 TTL 实现自动过期。
但 TTL 只能清除“单条”缓存,无法联动清除与该租户相关的聚合缓存、本地 Caffeine 缓存、Spring Cache 注解产生的多级缓存。
Redis 2.8+ 提供的 Keyspace Notification 可以把“键过期事件”推送给客户端,利用这一机制即可在“键过期瞬间”触发租户级缓存清理逻辑,实现“一条过期、全局联动”的效果,避免缓存漂移与脏数据。

知识点

  1. Redis Keyspace Notification 机制
    • 事件类型:expired / evicted / del …
    • 配置:notify-keyspace-events 设为 Ex(国内云厂商 Redis 默认关闭,需在控制台或参数组显式开启)。
    • 事件格式:keyevent@<db>:expired <key>
  2. Spring Data Redis 监听方式
    • RedisMessageListenerContainer + MessageListener 实现订阅。
    • 注意:** lettuce 连接池必须开启 shareNativeConnection=false**,否则订阅连接会被阻塞。
  3. 租户键设计
    • 统一前缀:tenant:{tenantId}:cache:{biz}:*
    • 过期事件里只能拿到“完整 key”,需用 正则或工具类 解析出 tenantId。
  4. 清理范围
    • Redis:使用 scan + unlink 批量删除该租户其余 key(避免阻塞)。
    • 本地:通过 Spring 的 CacheManager 获取 CaffeineCache,调用 invalidateAll()。
    • 集群节点:借助 Spring Cloud Bus + 自定义事件 广播 ClearTenantCacheRemoteEvent,保证多节点本地缓存一致性。
  5. 可靠性
    • Keyspace Notification 采用 Pub/Sub,不保证 100% 送达;核心场景仍需兜底“读时补偿”机制。
    • 高频过期场景需做 限流 + 异步线程池,防止清理任务打满业务线程。

答案

  1. 开启 Redis Keyspace 事件
    在云厂商控制台(阿里云、腾讯云、华为云)找到参数“notify-keyspace-events”,设置为 Ex;若自建 Redis,在 redis.conf 添加相同配置并重启。
  2. 定义租户键规则
    所有缓存键统一按“tenant:{tenantId}:cache:{biz}:{id}”拼装,并设置随机 TTL(30~60 s 抖动),防止缓存雪崩。
  3. 编写监听组件
    @Component
    public class TenantCacheCleanListener implements MessageListener {
        private static final Pattern TENANT_KEY_PATTERN = Pattern.compile("^tenant:(\\d+):cache:");
        @Autowired private RedisTemplate<String, Object> redisTemplate;
        @Autowired private CacheManager cacheManager;
        @Autowired private ApplicationEventPublisher publisher;
    
        @Override
        public void onMessage(Message message, byte[] pattern) {
            String key = new String(message.getBody(), StandardCharsets.UTF_8);
            Matcher m = TENANT_KEY_PATTERN.matcher(key);
            if (!m.find()) return;
            String tenantId = m.group(1);
            // 1. 清理 Redis 侧该租户其余 key
            cleanRedis(tenantId);
            // 2. 清理本地 Caffeine
            cleanLocal(tenantId);
            // 3. 广播到集群其它节点
            publisher.publishEvent(new ClearTenantCacheRemoteEvent(tenantId));
        }
    
        private void cleanRedis(String tenantId) {
            String pattern = "tenant:" + tenantId + ":cache:*";
            try (Cursor<byte[]> cursor = redisTemplate.getConnectionFactory()
                    .getConnection().scan(ScanOptions.scanOptions().match(pattern).count(1000).build())) {
                cursor.forEachRemaining(k -> redisTemplate.unlink(new String(k, StandardCharsets.UTF_8)));
            }
        }
    
        private void cleanLocal(String tenantId) {
            Cache cache = cacheManager.getCache("tenant-" + tenantId);
            if (cache instanceof CaffeineCache) {
                ((CaffeineCache) cache).clear();
            }
        }
    }
    
  4. 注册监听容器
    @Configuration
    public class RedisEventConfig {
        @Bean
        public RedisMessageListenerContainer container(RedisConnectionFactory factory,
                                                        TenantCacheCleanListener listener) {
            RedisMessageListenerContainer container = new RedisMessageListenerContainer();
            container.setConnectionFactory(factory);
            // 必须设置 shareNativeConnection=false,防止 lettuce 共享连接被阻塞
            if (factory instanceof LettuceConnectionFactory) {
                ((LettuceConnectionFactory) factory).setShareNativeConnection(false);
            }
            container.addMessageListener(listener, new PatternTopic("__keyevent@*__:expired"));
            return container;
        }
    }
    
  5. 集群广播(Spring Cloud Bus)
    @RemoteApplicationEventScan
    public class BusConfig { }
    
    @Component
    public class ClearTenantCacheRemoteEventListener {
        @EventListener
        public void onRemote(ClearTenantCacheRemoteEvent event) {
            Cache cache = cacheManager.getCache("tenant-" + event.getTenantId());
            if (cache instanceof CaffeineCache) {
                ((CaffeineCache) cache).clear();
            }
        }
    }
    
  6. 兜底策略
    • 读缓存时若返回 null,先查数据库再回写缓存,并设置短期 TTL,防止 Notification 丢失导致缓存穿透。
    • 对清理线程池做信号量限流,避免大批量过期时打满 CPU。

拓展思考

  1. 如果租户数量巨大,scan + unlink 仍可能造成 Redis 卡顿,可引入 Redis Lua 脚本 把“查找+删除”一次性放在服务端执行,减少往返 RTT。
  2. 对于金融级场景,可放弃 Keyspace Notification,改用 Redisson RMapCache 的 entryExpiredListener,它基于 Redis 的 Pub/Sub 但做了** ACK 重试**,可靠性更高。
  3. 在 Service Mesh 场景下,可把清理逻辑下沉到 Sidecar(如 Envoy + WASM),通过 Redis filter 监听过期事件,直接调用本地 Admin API 清缓存,实现语言无关的租户缓存治理。