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
@NoArgsConstructor
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
public class BaseEntity implements Serializable {
@Id
@TableId(value = "id", type = IdType.ASSIGN_UUID)
@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);
}
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();
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 {
ENTITY entity = commonBaseMapper().selectById(id);
// 不论是否为null,都要缓存 防止穿透
mapCache.put(id, entity, 10, TimeUnit.MINUTES);
// 如果是null就存储一个id为"null"的字符串做标记 防止穿透
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;
}
}