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; + } +}