Java 后端 / 系统课时

处理缓存穿透、击穿与雪崩

处理缓存穿透、击穿与雪崩

本课解决缓存失效后请求直接冲击数据库的问题。你将用空值缓存拦截不存在的数据,用互斥重建保护热点键,用随机过期时间分散失效时刻,并在入口限流,形成可落地的多层防护方案。

学习目标

  • 区分缓存穿透、缓存击穿与缓存雪崩的触发条件
  • 实现空值缓存、互斥重建和随机 TTL
  • 在缓存与数据库之前增加限流并验证效果

先判断风险发生在哪一层

缓存穿透是请求持续查询不存在的数据,缓存和数据库都无法命中。缓存击穿是某个热点键刚好过期,大量并发同时回源。缓存雪崩则是大量键在相近时刻失效,或 Redis 整体不可用,导致数据库瞬间承受集中流量。

三类问题不能只靠一种策略解决。空值缓存针对“数据不存在”,互斥重建和逻辑过期针对“热点键失效”,随机 TTL 针对“批量同时失效”,限流与降级则负责兜住超过系统容量的请求。

缓存风险与防护策略关系图

实现多层缓存保护

下面的 Spring Boot 3 示例提供一个商品查询接口。它使用 StringRedisTemplate 缓存 JSON,空值只保留 2 分钟,正常数据使用 30~40 分钟的随机 TTL;缓存未命中时通过带令牌的 Redis 互斥键限制重建者,并用 Lua 脚本原子释放锁。入口限流同样使用 Lua,把每个客户端每分钟最多 60 次请求作为最后一道保护。

java
package com.example.cache;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;

@SpringBootApplication
public class CacheRiskApplication {

    public static void main(String[] args) {
        SpringApplication.run(CacheRiskApplication.class, args);
    }

    public record Product(long id, String name) {}

    public record ApiResponse(String status, Product data, String message) {}

    @Repository
    static class ProductRepository {
        private final Map<Long, Product> data =
                Map.of(1L, new Product(1L, "机械键盘"));

        Product findById(long id) {
            System.out.println("DB query: " + id);
            return data.get(id);
        }
    }

    @Service
    static class ProductService {
        private static final String NULL_VALUE = "__NULL__";

        private static final DefaultRedisScript<Long> RELEASE_LOCK =
                new DefaultRedisScript<>(
                        "if redis.call('get', KEYS[1]) == ARGV[1] "
                                + "then return redis.call('del', KEYS[1]) "
                                + "else return 0 end",
                        Long.class);

        private static final DefaultRedisScript<Long> RATE_LIMIT =
                new DefaultRedisScript<>(
                        "local n = redis.call('incr', KEYS[1]); "
                                + "if n == 1 then redis.call('expire', KEYS[1], ARGV[1]) end; "
                                + "return n",
                        Long.class);

        private final StringRedisTemplate redis;
        private final ObjectMapper objectMapper;
        private final ProductRepository repository;

        ProductService(
                StringRedisTemplate redis,
                ObjectMapper objectMapper,
                ProductRepository repository) {
            this.redis = redis;
            this.objectMapper = objectMapper;
            this.repository = repository;
        }

        boolean allowRequest(String clientId) {
            Long count = redis.execute(
                    RATE_LIMIT,
                    List.of("rate:product:" + clientId),
                    "60");
            return count != null && count <= 60;
        }

        Product getById(long id) {
            String cacheKey = "cache:product:" + id;
            String cached = redis.opsForValue().get(cacheKey);
            if (cached != null) {
                return decode(cached);
            }

            String lockKey = "lock:cache:product:" + id;
            for (int attempt = 0; attempt < 5; attempt++) {
                String token = UUID.randomUUID().toString();
                Boolean locked = redis.opsForValue().setIfAbsent(
                        lockKey, token, Duration.ofSeconds(10));

                if (Boolean.TRUE.equals(locked)) {
                    try {
                        // 双重检查,避免等待期间其他线程已经完成重建。
                        cached = redis.opsForValue().get(cacheKey);
                        if (cached != null) {
                            return decode(cached);
                        }

                        Product product = repository.findById(id);
                        if (product == null) {
                            redis.opsForValue().set(
                                    cacheKey, NULL_VALUE, Duration.ofMinutes(2));
                            return null;
                        }

                        long ttlMinutes =
                                30 + ThreadLocalRandom.current().nextLong(11);
                        redis.opsForValue().set(
                                cacheKey,
                                objectMapper.writeValueAsString(product),
                                Duration.ofMinutes(ttlMinutes));
                        return product;
                    } catch (Exception ex) {
                        throw new IllegalStateException("缓存重建失败", ex);
                    } finally {
                        redis.execute(RELEASE_LOCK, List.of(lockKey), token);
                    }
                }

                sleep(50);
                cached = redis.opsForValue().get(cacheKey);
                if (cached != null) {
                    return decode(cached);
                }
            }

            throw new ResponseStatusException(
                    HttpStatus.SERVICE_UNAVAILABLE, "缓存正在重建");
        }

        private Product decode(String value) {
            if (NULL_VALUE.equals(value)) {
                return null;
            }
            try {
                return objectMapper.readValue(value, Product.class);
            } catch (Exception ex) {
                throw new IllegalStateException("缓存数据格式错误", ex);
            }
        }

        private void sleep(long millis) {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
                throw new IllegalStateException("等待缓存重建时被中断", ex);
            }
        }
    }

    @RestController
    @RequestMapping("/products")
    static class ProductController {
        private final ProductService service;

        ProductController(ProductService service) {
            this.service = service;
        }

        @GetMapping("/{id}")
        ResponseEntity<ApiResponse> get(
                @PathVariable long id,
                @RequestHeader(defaultValue = "demo") String clientId) {
            if (!service.allowRequest(clientId)) {
                return ResponseEntity.status(429).body(
                        new ApiResponse("RATE_LIMITED", null, "请求过于频繁"));
            }

            Product product = service.getById(id);
            if (product == null) {
                return ResponseEntity.status(404).body(
                        new ApiResponse("NOT_FOUND", null, "商品不存在"));
            }
            return ResponseEntity.ok(
                    new ApiResponse("OK", product, null));
        }
    }
}

运行前需要启动 Redis,并在项目中引入 spring-boot-starter-data-redis 与 spring-boot-starter-web。应用启动后执行以下请求;<PORT> 替换为实际端口,Spring Boot 默认通常为 8080。

bash
curl -i -H "clientId: user-1" http://localhost:<PORT>/products/1
curl -i -H "clientId: user-1" http://localhost:<PORT>/products/999
curl -i -H "clientId: user-1" http://localhost:<PORT>/products/999
redis-cli TTL cache:product:999

预期结果

text
HTTP/1.1 200
{"status":"OK","data":{"id":1,"name":"机械键盘"},"message":null}

HTTP/1.1 404
{"status":"NOT_FOUND","data":null,"message":"商品不存在"}

HTTP/1.1 404
{"status":"NOT_FOUND","data":null,"message":"商品不存在"}

<TTL_SECONDS>

清空相关缓存后连续查询不存在的商品,控制台只应出现一次 DB query: 999。<TTL_SECONDS> 是小于等于 120 的动态正整数,说明空值缓存已经生效。

何时改用逻辑过期

互斥重建会让未获得锁的请求短暂等待,适合允许几十到几百毫秒抖动的普通热点。对首页配置、爆款商品等必须持续可读的数据,可以把业务值与逻辑过期时间一起保存;读到过期值时先返回旧数据,再由一个获得锁的线程异步重建。

逻辑过期牺牲了短时间内的强一致性,换取稳定响应时间。它仍需要互斥重建、后台线程池容量限制和失败告警,否则大量过期热点可能同时占满重建线程。

上线前检查边界

空值 TTL 应明显短于正常数据 TTL,避免真实数据创建后长期不可见。随机 TTL 应在基础 TTL 上增加可控抖动,而不是完全随机。缓存重建锁的租约必须覆盖正常查询耗时,同时使用令牌校验释放,防止误删其他请求的新锁。

限流阈值应根据接口容量和客户端维度设置。Redis 故障时还要准备本地限流、熔断或降级结果,因为缓存保护不能把 Redis 自身变成新的单点。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

处理缓存穿透、击穿与雪崩

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通