test(cache): 集成测试穿透防护(空值缓存,loader 仅调用一次)

This commit is contained in:
root
2026-06-26 05:06:05 +08:00
parent 9abff913e5
commit b5a649110e

View File

@@ -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<User> 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;
}
}