== null 判断
1. 检查对象是否未初始化(没有内存引用)
2. 若Map未被实例化(比如Redis查询返回null),此时使用任何方法都会抛出NullPointerException
3. 适用于检测缓存未命中且Redis返回null的情况
isEmpty() 判断
1. 检查已存在的Map对象是否没有键值对(size==0)
2. 当Redis查询到空的Hash结构时(比如新建的对象),entries() 会返回空Map而非null
以如下代码为例:
这里shopInfo != null,但 shopInfo.isEmpty() == true
public Result queryById(Long id) {
// 1.设置缓存中的key名
String key = RedisConstants.CACHE_SHOP_KEY + id;
// 2.查询缓存中的数据,并判断是否存在(商铺信息)
Map<Object, Object> shopInfo = stringRedisTemplate.opsForHash().entries(key);
// 3.如果存在,则直接返回数据
if (shopInfo != null && !shopInfo.isEmpty()) {
Shop shop = BeanUtil.fillBeanWithMap(shopInfo, new Shop(), false);
return Result.ok(shop);
} else {
// 如果缓存中不存在,则查询数据库
Shop shop = getById(id);
if (shop != null) {
// 如果数据库中存在该数据,则将数据存入缓存中
stringRedisTemplate.opsForHash().putAll(key, BeanUtil.beanToMap(shop, new HashMap<>(),
CopyOptions.create()
.setIgnoreNullValue(true)
.setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString())));
return Result.ok(shop);
} else {
// 数据库中不存在,则返回错误信息
return Result.fail("店铺信息不存在");
}
}
}
1145

被折叠的 条评论
为什么被折叠?



