当开始我们写的商品分类业务层,是前台每次直接访问数据库进行数据读取,这样的设计在高并发的情况下容易导致数据库崩溃的发送,因此我们需要进行优化处理
为什么使用redis
因为redis的数据存在缓存中所有读取快,压力相对于直接访问数据库小
优化思路:
用户在第一次访问的时候,先去拿取redis缓存中的数据,判断为空,然后查询数据库存入redis的中央缓存中,并将数据返回到前台展示给客户,下次访问直接从redis的缓存中读取
为什么要设计中央缓存
因为如果要使用集群,单将数据存入一个服务器中,进行负载均衡时数据不能同步
Redis的使用
查询数据库的方法
public List<ProductType> getAllDataBy_db(){
//从数据库查询出所有数据
List<ProductType> productTypes;
productTypes = productTypeMapper.selectList(null);
//将集合转换为字符串
String ProData = JSON.toJSONString(productTypes);
redisClient.set(CommonConstant.REDIS_KEY, ProData);
return productTypes;
}
查询出的数据进行拼装
private void makeStructure(List<ProductType> productTypes, List<ProductType> productTypes1) {
/**
* 准备一个Map 先将所有的数据装入map中
* 在根据条件去取出存入子集合中
*/
Map<Long,ProductType> map = new HashMap<>();
//遍历出所有得数据 存入map中
productTypes1.forEach(e->{
map.put(e.getId(), e);
});
for (ProductType productType : productTypes1) {
//如果pid==0则是最高级分类
if (productType.getPid() == 0) {
productTypes.add(productType);
} else {
//获取父级
ProductType parent = map.get(productType.getPid());
//创建子集合
List<ProductType> children = parent.getChildren();