public List<SimpleGoodsInfo> getSimpleGoodsInfoByTableId(TableId tableId) {
// 获取商品的简单信息, 可以从 redis cache 中去拿, 拿不到需要从 DB 中获取并保存到 Redis 里面
// Redis 中的 KV 都是字符串类型
List<Object> goodIds = tableId.getIds().stream()
.map(i -> i.getId().toString()).collect(Collectors.toList());
// FIXME 如果 cache 中查不到 goodsId 对应的数据, 返回的是 null, [null, null]
List<Object> cachedSimpleGoodsInfos = redisTemplate.opsForHash()
.multiGet(GoodsConstant.ECOMMERCE_GOODS_DICT_KEY, goodIds)
.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
// 如果从 Redis 中查到了商品信息, 分两种情况去操作
if (CollectionUtils.isNotEmpty(cachedSimpleGoodsInfos)) {
// 1. 如果从缓存中查询出所有需要的 SimpleGoodsInfo
if (cachedSimpleGoodsInfos.size() == goodIds.size()) {
log.info("get simple goods info by ids (from cache): [{}]",
JSON.toJSONString(goodIds));
return parseCachedGoodsInfo(cachedSimpleGoodsInfos);
} else {
// 2. 一半从数据表中获取 (right), 一半从 redis cache 中获取 (left)
List<SimpleGoodsInfo> left = parseCachedGoodsInfo(cachedSimpleGoodsInfos);
// 取差集: 传递进来的参数 - 缓存中查到的 = 缓存中没有的
Collection<Long> subtractIds = CollectionUtils.subtract(
goodIds.stream()
.map(g -> Long.valueOf(g.toString())).collect(Collectors.toList()),
left.stream()
.map(SimpleGoodsInfo::getId).collect(Collectors.toList())
);
// 缓存中没有的, 查询数据表并缓存
List<SimpleGoodsInfo> right = queryGoodsFromDBAndCacheToRedis(
new TableId(subtractIds.stream().map(TableId.Id::new)
.collect(Collectors.toList()))
);
// 合并 left 和 right 并返回
log.info("get simple goods info by ids (from db and cache): [{}]",
JSON.toJSONString(subtractIds));
return new ArrayList<>(CollectionUtils.union(left, right));
}
} else {
// 从 redis 里面什么都没有查到
return queryGoodsFromDBAndCacheToRedis(tableId);
}
}
private List<SimpleGoodsInfo> queryGoodsFromDBAndCacheToRedis(TableId tableId) {
// 从数据表中查询数据并做转换
List<Long> ids = tableId.getIds().stream()
.map(TableId.Id::getId).collect(Collectors.toList());
log.info("get simple goods info by ids (from db): [{}]",
JSON.toJSONString(ids));
List<EcommerceGoods> ecommerceGoods = IterableUtils.toList(
ecommerceGoodsDao.findAllById(ids)
);
List<SimpleGoodsInfo> result = ecommerceGoods.stream()
.map(EcommerceGoods::toSimple).collect(Collectors.toList());
// 将结果缓存, 下一次可以直接从 redis cache 中查询
log.info("cache goods info: [{}]", JSON.toJSONString(ids));
Map<String, String> id2JsonObject = new HashMap<>(result.size());
result.forEach(g -> id2JsonObject.put(
g.getId().toString(), JSON.toJSONString(g)
));
// 保存到 Redis 中
redisTemplate.opsForHash().putAll(
GoodsConstant.ECOMMERCE_GOODS_DICT_KEY, id2JsonObject);
return result;
}