如何把推荐列表缓存到 Redis 并设置用户级 TTL?

解读

国内互联网面试中,高并发读与千人千面推荐是高频考点。面试官想确认:

  1. 你是否理解Struts 拦截器/Action 与 Redis 的衔接点;
  2. 能否把用户维度、业务维度、缓存维度三要素同时落地;
  3. 是否具备缓存穿透、雪崩、热点 Key的线上防护意识。

答题时先给出整体架构图(口述),再落到代码级实现,最后补充运维级兜底方案。

知识点

  • Struts2 拦截器栈:在 struts.xml 中自定义 cacheInterceptor,插入默认栈,保证 Action 执行前后都能操作 Redis。
  • Redis 数据结构选择:推荐列表有序且可分页,采用 List + LRANGE;若需去重或实时打分,用 ZSET。
  • Key 规范:app:struts:rec:{userId}:{scene},冒号分隔方便 Redis Cluster 分片。
  • TTL 策略:以 用户最后一次访问时间为基准,采用 滑动过期(每次命中重置 TTL),防止“一刀切”造成缓存雪崩。
  • 序列化:国内生产环境统一用 Protobuf/Kryo,比 JDK 序列化节省 60% 空间,降低 Redis 内存单价成本。
  • 本地兜底:当 Redis 单节点宕机或 连接池被打满,通过 Guava LoadingCache 做 本地短路,保证 0 级降级。
  • 批刷方案:夜间低峰期,通过 XXL-JOB 分片任务,异步回写 Redis,避免 缓存击穿。

答案

  1. 自定义拦截器 RecommendCacheInterceptor
    实现 com.opensymphony.xwork2.interceptor.AbstractInterceptor,在 intercept(ActionInvocation invocation) 中:

    • 从 Session 或 JWT 解析 userId,线程内透传;
    • 组装 Redis Key:String key = "app:struts:rec:" + userId + ":home";
    • 先读 Redis:List<String> recList = redisTemplate.opsForList().range(key, 0, 19);
    • 若命中,重置 TTL = 30 分钟;redisTemplate.expire(key, Duration.ofMinutes(30));
    • 若未命中,放行到 Action,业务线程查询 DB+算法,返回后 pipeline 写回:
      redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
          connection.lPush(keyRaw, recArray);
          connection.expire(keyRaw, 1800);
          return null;
      });
      
    • 把结果塞入 ActionContext.getContext().put("recList", recList),JSP/FreeMarker 直接渲染。
  2. 配置入口
    在 struts.xml 中:

    <package name="front" extends="struts-default">
        <interceptors>
            <interceptor name="recCache" class="com.xxx.interceptor.RecommendCacheInterceptor"/>
            <interceptor-stack name="appStack">
                <interceptor-ref name="recCache"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="appStack"/>
        <action name="home" class="com.xxx.action.HomeAction">
            <result name="success">/home.jsp</result>
        </action>
    </package>
    
  3. 用户级 TTL 细节

    • 滑动过期:每次命中都 EXPIRE,保证活跃用户永不过期,沉默用户自然淘汰;
    • 最大 TTL 上限:防止 Key 永驻,可在 夜间定时任务 扫描 idle time > 7 天 的 Key 统一删除;
    • Redis 6 过期策略:利用 lazy expire + 每秒 10 次抽样,CPU 抖动可控。
  4. 线上高可用

    • Redis Cluster 三主三从,同城双活,半同步复制;
    • 连接池参数:maxTotal=500,maxWaitMillis=200,testOnBorrow=true;
    • 熔断:Sentinel 监控 OPS > 8W 或 RT > 50ms 时,降级到本地缓存;
    • 大 Key 热 Key 监控:Redis 内存 > 10MB 或 QPS > 5K 自动 拆分+本地缓存。

拓展思考

  • 多级缓存:在 CDN 边缘节点缓存 Top 100 用户的推荐结果,回源到 Redis,回源到 DB,三层防护;
  • 实时特征变更:当用户 点击/下单 后,通过 Canal 监听 binlog,推送 Kafka,Flink 实时更新 Redis 中的 ZSET 分数,实现 秒级兴趣漂移;
  • 灰度刷新:利用 Redis Lua 脚本实现 compare-and-set,按用户百分比逐步刷新,防止 全量重建带来的 缓存雪崩;
  • 成本优化:Redis on Flash 或 Pika 冷数据落盘,内存成本下降 70%,适合 长尾用户;
  • 合规:若推荐列表含 用户隐私标签,需 AES 加密后落 Redis,Key 与 IV 存 KMS,满足 《个人信息保护法》 要求。