黄同学的后端和 Agent 笔记开通
Hello 后端

动手做:复现缓存击穿和穿透

黄同学约 9 分钟读完免费

在 shop 项目里写一个带缓存的商品详情接口,再用一个小程序让 200 个请求同时去查一件缓存刚被删掉的商品,数一数数据库被查了几次;加上互斥锁和双重检查以后再数一次,应该正好是 1 次。接着用 100 个不存在的商品请求复现缓存穿透,加上缓存空值,查库次数从 100 降到 1。最后在组件里看一眼雪崩。

要先学过:

这一页的类都放在一个单独的包 com.shop.cachelab 里,接口都在 /cache-lab 下面,不会和你在别的动手做页里写的 ProductService、/products 撞名。做完以后整个包删掉就行。

步骤

  1. 起 MySQL 和 Redis,顺手删掉以前留下的 7 号商品的缓存:

    bash
    cd hello-backend
    docker compose up -d --wait
    docker compose exec redis redis-cli ping
    docker compose exec redis redis-cli DEL product:detail:7

    hello-backend 换成你那个目录实际的路径。ping 回 PONG 就行;DEL 回 (integer) 1 或 (integer) 0 都对,读 String 和 Hash 时照敲过的话会留下这个键,回的就是 1。

    再确认商品表里有 7 号商品:

    bash
    docker compose exec mysql mysql -uroot -psecret --default-character-set=utf8mb4 shop -e "SELECT id, name, price FROM products"

    能看到 7、8、9 三行就对了,第一行之前还会有一行 Using a password on the command line interface can be insecure 的警告,不用管。报 Unknown database 'shop' 的,照动手做:建项目、连上 MySQL、打通第一个接口第 1 步执行一遍 lab.sql。

  2. 给项目加上 Redis。做过动手做:用 Redis 存登录验证码的,这一步已经做过了,直接跳到第 3 步。

    打开 ~/hb-spring/shop/pom.xml,在 <dependencies> 里加上:

    xml
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    打开 src/main/resources/application.yml,在原来的 spring: 下面加 data: 那一段。文件里不能出现两个顶格的 spring:,不然启动时报 duplicate key:

    yaml
    spring:
      # application、datasource 这些原来的配置原样留着
      data:
        redis:
          host: localhost
          port: 6379
          timeout: 2s
  3. 写查库的 Mapper。新建目录 src/main/java/com/shop/cachelab,这一页的三个类都放在里面:

    java
    // src/main/java/com/shop/cachelab/CacheLabMapper.java
    package com.shop.cachelab;
    
    import org.apache.ibatis.annotations.Mapper;
    import org.apache.ibatis.annotations.Select;
    
    import com.shop.entity.Product;
    
    @Mapper
    public interface CacheLabMapper {
    
        @Select("SELECT id, name, price, stock FROM products WHERE id = #{id}")
        Product findById(Long id);
    }
  4. 写 Service。这是先查缓存再查库的写法,先不加任何保护。为了数清楚查了几次库,查库前给计数器加 1;为了让一次查询像真的复杂查询那样慢,查库前先睡 50 ms:

    java
    // src/main/java/com/shop/cachelab/CacheLabService.java
    package com.shop.cachelab;
    
    import java.time.Duration;
    import java.util.concurrent.atomic.AtomicInteger;
    
    import org.springframework.data.redis.core.StringRedisTemplate;
    import org.springframework.stereotype.Service;
    
    import com.shop.entity.Product;
    
    import tools.jackson.databind.ObjectMapper;
    
    @Service
    public class CacheLabService {
    
        private final StringRedisTemplate redis;
        private final ObjectMapper objectMapper;
        private final CacheLabMapper mapper;
        private final AtomicInteger dbCount = new AtomicInteger();   // 查了几次库
    
        public CacheLabService(StringRedisTemplate redis, ObjectMapper objectMapper, CacheLabMapper mapper) {
            this.redis = redis;
            this.objectMapper = objectMapper;
            this.mapper = mapper;
        }
    
        public Product getDetail(Long id) {
            String key = "product:detail:" + id;
            String cached = redis.opsForValue().get(key);
            if (cached != null) {
                return objectMapper.readValue(cached, Product.class);   // 命中
            }
            Product product = loadFromDb(id);                           // 没命中,查库
            if (product != null) {
                redis.opsForValue().set(key, objectMapper.writeValueAsString(product), Duration.ofMinutes(30));
            }
            return product;
        }
    
        /** 查库。故意先睡 50 ms,模拟一个要查好几张表的慢查询 */
        private Product loadFromDb(Long id) {
            dbCount.incrementAndGet();
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return mapper.findById(id);
        }
    
        public int dbCount() {
            return dbCount.get();
        }
    
        /** 删掉这个商品的缓存,计数器清零,每次实验前调一次 */
        public void reset(Long id) {
            redis.delete("product:detail:" + id);
            dbCount.set(0);
        }
    }
  5. 写接口。商品不存在时回 404,正文为空:

    java
    // src/main/java/com/shop/cachelab/CacheLabController.java
    package com.shop.cachelab;
    
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.shop.entity.Product;
    
    @RestController
    @RequestMapping("/cache-lab")
    public class CacheLabController {
    
        private final CacheLabService service;
    
        public CacheLabController(CacheLabService service) {
            this.service = service;
        }
    
        @GetMapping("/products/{id}")
        public ResponseEntity<Product> get(@PathVariable Long id) {
            Product product = service.getDetail(id);
            return product == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(product);
        }
    
        @GetMapping("/db-count")
        public int dbCount() {
            return service.dbCount();
        }
    
        @PostMapping("/reset/{id}")
        public void reset(@PathVariable Long id) {
            service.reset(id);
        }
    }
  6. 写一个同时发 200 个请求的小程序。它不属于 shop 项目,单独放在 ~/hb-spring/burst 里,用 java Burst.java 直接跑。它先调 /cache-lab/reset/{id} 删缓存、清计数器,再让 200 个线程都等在同一个 CountDownLatch 上,一声令下同时发出请求,最后打印状态码、响应内容有几种、查了几次库:

    bash
    mkdir -p ~/hb-spring/burst
    cd ~/hb-spring/burst
    java
    // ~/hb-spring/burst/Burst.java
    import java.net.URI;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.TreeMap;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    
    public class Burst {
        public static void main(String[] args) throws Exception {
            int n = Integer.parseInt(args[0]);          // 同时发几个请求
            String id = args[1];                        // 查哪件商品
            String base = "http://localhost:8080/cache-lab";
            HttpClient client = HttpClient.newBuilder()
                    .version(HttpClient.Version.HTTP_1_1)
                    .build();
    
            // 先删掉这件商品的缓存,查库计数器清零
            client.send(HttpRequest.newBuilder(URI.create(base + "/reset/" + id))
                            .POST(HttpRequest.BodyPublishers.noBody()).build(),
                    HttpResponse.BodyHandlers.ofString());
    
            HttpRequest get = HttpRequest.newBuilder(URI.create(base + "/products/" + id)).build();
            CountDownLatch start = new CountDownLatch(1);
            List<Future<HttpResponse<String>>> futures = new ArrayList<>();
            try (ExecutorService pool = Executors.newFixedThreadPool(n)) {
                for (int i = 0; i < n; i++) {
                    futures.add(pool.submit(() -> {
                        start.await();                  // 都等在这里
                        return client.send(get, HttpResponse.BodyHandlers.ofString());
                    }));
                }
                Thread.sleep(500);                      // 等 n 个线程都就位
                start.countDown();                      // 一声令下,同时发出
    
                Map<Integer, Integer> codes = new TreeMap<>();
                Set<String> bodies = new HashSet<>();
                for (Future<HttpResponse<String>> f : futures) {
                    HttpResponse<String> r = f.get();
                    codes.merge(r.statusCode(), 1, Integer::sum);
                    bodies.add(r.body());
                }
                System.out.println("status codes: " + codes);
                System.out.println("distinct bodies: " + bodies.size());
            }
    
            HttpResponse<String> count = client.send(
                    HttpRequest.newBuilder(URI.create(base + "/db-count")).build(),
                    HttpResponse.BodyHandlers.ofString());
            System.out.println("db queries: " + count.body());
        }
    }

    输出用英文,是为了在 Windows 的终端里也不出乱码。status codes: {200=200} 的意思是状态码 200 的响应有 200 个。

  7. 启动项目,不加保护先跑一次:

    bash
    cd ~/hb-spring/shop
    ./mvnw spring-boot:run

    看到 Started ShopApplication 以后,另开一个终端:

    bash
    cd ~/hb-spring/burst
    java Burst.java 200 7
    text
    status codes: {200=200}
    distinct bodies: 1
    db queries: 183

    200 个响应都是 200,内容都一样,这一步没问题;要看的是最后一行。200 个请求同时到,第一个查库的要 50 ms 后才写回缓存,在这之前到的都没命中、都去查了库。你看到的数每次都不一样,多半在几十到 200 之间,电脑越快、请求挤得越紧,数越大,多跑两三次就能看出来。

  8. 加上互斥锁。先自己想一想,再点开答案对一下:

    • 在 CacheLabService 里加一个 ConcurrentHashMap<Long, ReentrantLock>,一个商品一把锁。
    • getDetail 没命中时先拿锁,拿到锁以后再查一次缓存,有了就直接返回,还没有才查库、写回。unlock() 放在 finally 里。
    答案

    CacheLabService 里加一个字段,getDetail 整个换成下面这样,文件开头加上 import java.util.concurrent.ConcurrentHashMap; 和 import java.util.concurrent.locks.ReentrantLock;:

    java
    private final ConcurrentHashMap<Long, ReentrantLock> locks = new ConcurrentHashMap<>();
    
    public Product getDetail(Long id) {
        String key = "product:detail:" + id;
        String cached = redis.opsForValue().get(key);
        if (cached != null) {
            return objectMapper.readValue(cached, Product.class);
        }
        ReentrantLock lock = locks.computeIfAbsent(id, k -> new ReentrantLock());
        lock.lock();
        try {
            cached = redis.opsForValue().get(key);          // 拿到锁以后,再查一次缓存
            if (cached != null) {
                return objectMapper.readValue(cached, Product.class);
            }
            Product product = loadFromDb(id);
            if (product != null) {
                redis.opsForValue().set(key, objectMapper.writeValueAsString(product), Duration.ofMinutes(30));
            }
            return product;
        } finally {
            lock.unlock();
        }
    }

    锁必须从 locks 里按 id 取,同一件商品的请求拿到的才是同一把锁;每次 new ReentrantLock() 的话,每个请求各锁各的,等于没锁。

  9. 回到第一个终端,Ctrl + C 停掉项目,再 ./mvnw spring-boot:run 启动,然后在第二个终端再跑一次:

    bash
    java Burst.java 200 7
    text
    status codes: {200=200}
    distinct bodies: 1
    db queries: 1

    这次最后一行一定是 1,多跑几次也是 1。第一个拿到锁的请求查库、写回缓存,其余 199 个排队拿锁,拿到以后再查一次缓存就命中了。

    想看看少了「再查一次缓存」会怎样,可以把锁里面「再查一次缓存」的那几行先注释掉,再试一次:查库次数又回到一百多,而且这次是排着队一个一个查的,Burst 要多等好几秒才打印结果。试完记得改回来。

  10. 复现缓存穿透。用一个不存在的商品 999999,一个接一个地请求 100 次,再看查了几次库:

    bash
    curl -s -X POST localhost:8080/cache-lab/reset/999999
    for i in $(seq 100); do curl -s -o /dev/null -w '%{http_code}\n' localhost:8080/cache-lab/products/999999; done | sort | uniq -c
    curl -s localhost:8080/cache-lab/db-count; echo

    第二行把 100 个状态码数一数,第三行打出查库次数(后面的 echo 只是换个行):

    text
        100 404
    100

    100 个请求一个接一个来,不是同时到的,互斥锁帮不上忙:库里没有这件商品,什么都不会写回缓存,所以每个请求都查了一次库。

  11. 加上缓存空值。提示:查库得到 null 时,往 Redis 写一个空字符串,过期时间 60 秒;读到空字符串,直接返回 null。getDetail 里有两处读缓存,两处都要先认出空字符串,再去解析 JSON,空字符串交给 readValue 会抛异常。

    答案

    把两处解析挪进一个小方法,getDetail 整个换成这样:

    java
    public Product getDetail(Long id) {
        String key = "product:detail:" + id;
        String cached = redis.opsForValue().get(key);
        if (cached != null) {
            return parse(cached);
        }
        ReentrantLock lock = locks.computeIfAbsent(id, k -> new ReentrantLock());
        lock.lock();
        try {
            cached = redis.opsForValue().get(key);          // 拿到锁以后,再查一次缓存
            if (cached != null) {
                return parse(cached);
            }
            Product product = loadFromDb(id);
            if (product == null) {
                redis.opsForValue().set(key, "", Duration.ofSeconds(60));   // 库里没有:空标记,60 秒
            } else {
                redis.opsForValue().set(key, objectMapper.writeValueAsString(product), Duration.ofMinutes(30));
            }
            return product;
        } finally {
            lock.unlock();
        }
    }
    
    /** 空字符串是空标记,表示库里没有;别的才是商品的 JSON */
    private Product parse(String cached) {
        return cached.isEmpty() ? null : objectMapper.readValue(cached, Product.class);
    }
  12. 重启项目,把第 10 步的三条命令再敲一遍:

    text
        100 404
    1

    还是 100 个 404,查库只剩 1 次:第一次查完写了空标记,后面 99 次在 Redis 就知道「没有」了。去 Redis 里看一眼这个空标记(在 hello-backend 目录里敲):

    bash
    docker compose exec redis redis-cli GET product:detail:999999
    docker compose exec redis redis-cli TTL product:detail:999999
    text
    ""
    (integer) 52

    "" 就是空字符串。TTL 在 1 到 60 之间,取决于你隔了多久敲;超过 60 秒才敲的,第一行是 (nil)、第二行是 -2,说明空标记已经过期了,重新跑一遍第 10 步的命令再看。

  13. 想一想:shop 部署了两台,同时有 200 个请求分到两台上查 7 号商品,查库会是几次?要做到不管几台都只查 1 次,锁应该放在哪?想好了再点开。

    答案

    两次。ReentrantLock 是每台机器自己内存里的对象,两台各有各的锁,各放一个请求去查库。台数少时这样通常够用;非要全局只查一次,就要把锁放在几台机器都能访问的地方,也就是 Redis 里,做法在用 SET NX 加锁讲。

在组件里看雪崩

雪崩要上万个键同时过期,在自己电脑上不好复现,用组件看。下面是缓存击穿那个组件的雪崩模式:先不勾「过期时间加随机数」播一遍,看 04:00 那一步同时查库的请求数;勾上再播一遍,比较两次柱状图的高度;最后点「让 Redis 挂掉」。道理在缓存雪崩讲过。

在新窗口打开

做不出来时

  • 请求回 500,项目的日志里有 Unable to connect to Redis:Redis 没开着。在 hello-backend 目录里 docker compose ps 看 redis 那一行是不是在运行,不是就 docker compose up -d --wait。
  • 启动时报错,日志里有 duplicate key:application.yml 里写了两个顶格的 spring:,把 data: 那一段挪进原来的 spring: 下面。
  • java Burst.java 报 ConnectException:项目没起来,或者不在 8080 端口。看第一个终端里有没有 Started ShopApplication。
  • 第 7 步每个请求都是 404:shop 库里没有 7 号商品,照第 1 步重新执行 lab.sql。
  • 第 7 步不加保护,查库次数也只有 1、2 次:看看 loadFromDb 里的 Thread.sleep(50) 是不是漏了。没有这 50 ms,查库太快,第一个请求写回缓存时后面的请求还没到。
  • 第 9 步加了锁,查库次数还是一百多:锁里面没有再查一次缓存,或者锁是每次 new 出来的,回第 8 步对一下答案。
  • 第 11 步以后请求 999999 回 500,日志里是 Jackson 解析出错:有一处读缓存的地方没先判断空字符串,就交给了 readValue。
  • 改了代码,结果和没改一样:要先 Ctrl + C 停掉项目再重新启动,改动才会生效。

做完了

第 7 步查库几十到两百次,第 9 步正好 1 次;第 10 步查库 100 次,第 12 步 1 次,GET 到的是 "":这几个数对上了,就是做对了。

收尾:在第一个终端 Ctrl + C 停掉项目。这一页的代码后面用不到,删掉 cachelab 这个包和 Burst.java 所在的目录:

bash
rm -rf ~/hb-spring/shop/src/main/java/com/shop/cachelab ~/hb-spring/burst

在 hello-backend 目录里删掉这一页留下的键:

bash
docker compose exec redis redis-cli DEL product:detail:7 product:detail:999999

pom.xml 里的 Redis 依赖、application.yml 里 spring.data.redis 那一段留着,后面的动手做页还要用。

下一节讲 Redis 为什么这么快:单线程为什么还快