SpringCloud整合Redis高并发下缓存穿透问题

采用线程同步锁解决

 

public /*synchronized*/ List findAll(){
    List deparments = departmentRedis.getList("mysql:findAll:deparment");
    //并发条件下存在缓存穿透的问题
    //双重检测
    if(null == deparments){
        synchronized(this){
            deparments = departmentRedis.getList("mysql:findAll:deparment");

            if(deparments == null) {
                System.out.println("查询数据库....");
                //redis缓存为null
                deparments = departmentRepository.findAll();
                if(deparments != null){
                    departmentRedis.add("mysql:findAll:deparment", 5L, deparments);
                }
            }else{
                System.out.println("查询缓存..");
            }
        }
    }else{
        System.out.println("查询缓存..");
    }
    return deparments;
}

你可能感兴趣的:(redis)