From b5a649110e6e199930e3dff3c11f3a225b5a38c4 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 26 Jun 2026 05:06:05 +0800 Subject: [PATCH] =?UTF-8?q?test(cache):=20=E9=9B=86=E6=88=90=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E7=A9=BF=E9=80=8F=E9=98=B2=E6=8A=A4(=E7=A9=BA?= =?UTF-8?q?=E5=80=BC=E7=BC=93=E5=AD=98,loader=20=E4=BB=85=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E4=B8=80=E6=AC=A1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../integration/CachePenetrationTest.java | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/test/java/com/njcn/middle/cache/integration/CachePenetrationTest.java diff --git a/src/test/java/com/njcn/middle/cache/integration/CachePenetrationTest.java b/src/test/java/com/njcn/middle/cache/integration/CachePenetrationTest.java new file mode 100644 index 0000000..144457e --- /dev/null +++ b/src/test/java/com/njcn/middle/cache/integration/CachePenetrationTest.java @@ -0,0 +1,59 @@ +package com.njcn.middle.cache.integration; + +import com.njcn.middle.cache.template.RedisCacheEnhanceTemplate; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringBootConfiguration; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** 集成测试:回源返回 null 时缓存空值标记,二次查询命中空标记、loader 不再被调用。 */ +@ExtendWith(RedisAvailableCondition.class) +@SpringBootTest(classes = CachePenetrationTest.TestApp.class, + properties = {"redis-cache.key-prefix=it-cache:", "redis-cache.null-ttl-seconds=30"}) +class CachePenetrationTest { + + @Autowired + private RedisCacheEnhanceTemplate cache; + + @Test + void nullResultCachedAndLoaderCalledOnce() { + String key = "pen:missing:1"; + cache.delete(key); + + AtomicInteger calls = new AtomicInteger(); + Supplier loader = () -> { + calls.incrementAndGet(); + return null; // 数据不存在 + }; + + assertNull(cache.getOrLoad(key, User.class, 60, loader)); + assertNull(cache.getOrLoad(key, User.class, 60, loader)); // 命中空值标记 + assertEquals(1, calls.get()); + + cache.delete(key); + } + + @SpringBootConfiguration + @EnableAutoConfiguration + static class TestApp { + } + + @Data + @AllArgsConstructor + @NoArgsConstructor + static class User { + private Long id; + private String name; + } +}