fix(common): Fix cache penetration issue

This commit is contained in:
Sol 2025-06-11 10:02:22 +08:00
parent 71d41b675b
commit e6b2a76bef
2 changed files with 15 additions and 4 deletions

View file

@ -17,7 +17,7 @@ import java.util.Date;
@SuperBuilder @SuperBuilder
@NoArgsConstructor @NoArgsConstructor
@MappedSuperclass @MappedSuperclass
public abstract class BaseEntity implements Serializable { public class BaseEntity implements Serializable {
@Id @Id
@TableId(value = "id", type = IdType.ASSIGN_UUID) @TableId(value = "id", type = IdType.ASSIGN_UUID)
@OrderBy(asc = true, sort = 33) @OrderBy(asc = true, sort = 33)

View file

@ -370,6 +370,8 @@ public abstract class BaseService<ENTITY extends BaseEntity, PAGE_DTO extends Ba
return commonBaseRedissonClient().getMapCache(key); return commonBaseRedissonClient().getMapCache(key);
} }
private static final String NULL_PLACEHOLDER = "null";
/** /**
* 缓存查询 * 缓存查询
*/ */
@ -379,11 +381,20 @@ public abstract class BaseService<ENTITY extends BaseEntity, PAGE_DTO extends Ba
} }
RMapCache<String, ENTITY> mapCache = getRMapCache(); RMapCache<String, ENTITY> mapCache = getRMapCache();
if (mapCache.containsKey(id)) { if (mapCache.containsKey(id)) {
return mapCache.get(id); ENTITY entity = mapCache.get(id);
if (entity.getId().equals(NULL_PLACEHOLDER)) {
return null;
} else {
return entity;
}
} else { } else {
ENTITY entity = commonBaseMapper().selectById(id); ENTITY entity = commonBaseMapper().selectById(id);
// 不论是否为null,都要缓存 防止穿透 // 如果是null就存储一个id为"null"的字符串做标记 防止穿透
mapCache.put(id, entity, 10, TimeUnit.MINUTES); if (entity == null) {
mapCache.put(id, (ENTITY) BaseEntity.builder().id(NULL_PLACEHOLDER).build(), 10, TimeUnit.MINUTES);
} else {
mapCache.put(id, entity, 10, TimeUnit.MINUTES);
}
return entity; return entity;
} }
} }