介绍
此处在谷粒商城的商品product项目,CategoryServiceImpl的获取二级、三机分类
原理:将数据库的多次查询, 变成一次
List<CategoryEntity> selectList = baseMapper.selectList(null);
//1.查询所有一级分类
List<CategoryEntity> categorys1 = getParent_cid(selectList,0L);
//2.1查询每个一级分类的二级分类(k,v都为某个一级分类)
List<CategoryEntity> categoryEntities = getParent_cid(selectList,v.getCatId());
//2.2.1 封装二级分类的三机分类
List<CategoryEntity> level3category = getParent_cid(selectList,item2.getCatId());
//根据父类id,获取所有分类(子分类)
private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parent_cid) {
// return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
//根据父id获取两类
List<CategoryEntity> collect = selectList.stream().filter(item -> {
return item.getParentCid() == parent_cid;
}).collect(Collectors.toList());
return collect;
}
1).抽取查询分类的方法## 2).修改代码
@Override
public Map<String, List<Category2Vo>> getCatalogJson() {
//将数据库的多次查询, 变成一次
List<CategoryEntity> selectList = baseMapper.selectList(null);
//1.查询所有一级分类
List<CategoryEntity> categorys1 = getParent_cid(selectList,0L);
//2.封装数据
Map<String, List<Category2Vo>> parent_cid = categorys1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
//2.1查询每个一级分类的二级分类(k,v都为某个一级分类)
List<CategoryEntity> categoryEntities = getParent_cid(selectList,v.getCatId());
//2.2封装上面结果 (item2,item3为二级、三机分类)
List<Category2Vo> category2Vos = null;
if (categoryEntities != null) {
category2Vos = categoryEntities.stream().map(item2 -> {
Category2Vo category2Vo = new Category2Vo(v.getCatId().toString(), null, item2.getCatId().toString(), item2.getName());
//2.2.1 封装二级分类的三机分类
List<CategoryEntity> level3category = getParent_cid(selectList,item2.getCatId());
//2.2.2 把三机分类数据封装到Category3Vo,并且封装到二级分类Category2Vo
if (level3category != null) {
List<Category2Vo.Category3Vo> collect = level3category.stream().map(item3 -> {
Category2Vo.Category3Vo category3Vo = new Category2Vo.Category3Vo(item2.getCatId().toString(),item3.getCatId().toString(),item3.getName());
return category3Vo;
}).collect(Collectors.toList());
category2Vo.setCatalog3List(collect);
}
return category2Vo;
}).collect(Collectors.toList());
}
return category2Vos;
}));
return parent_cid;
}
//根据父类id,获取所有分类(子分类)
private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parent_cid) {
// return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
//根据父id获取两类
List<CategoryEntity> collect = selectList.stream().filter(item -> {
return item.getParentCid() == parent_cid;
}).collect(Collectors.toList());
return collect;
}
3).测试
4)总结
减少访问数据库的次数,可以更加吞吐量,优化项目
5).问题
虽然吞吐量有所提高,但不明显
继续关注下一节,缓存、分布式锁,更多优化