for(SysUser user : userList){
user.setA(this.XXXService.getByIdAndCustomSelectSql(user.getId()));
user.setB(this.XXXService.getByIdAndCustomSelectSql(user.getId()));
user.setC(this.XXXService.getByIdAndCustomSelectSql(user.getId()));
user.setD(this.XXXService.getByIdAndCustomSelectSql(user.getId()));
user.setE(this.XXXService.getByIdAndCustomSelectSql(user.getId()));
}这种List遍历,每一次set都会查询一次数据库,上面一条执行完了才能执行下一条,用多线程优化这个过程,怎样可以让五条同步执行?
user.setA(this.XXXService.getByIdAndCustomSelectSql(user.getId()));
user.setB(this.XXXService.getByIdAndCustomSelectSql(user.getId()));
user.setC(this.XXXService.getByIdAndCustomSelectSql(user.getId()));
user.setD(this.XXXService.getByIdAndCustomSelectSql(user.getId()));
user.setE(this.XXXService.getByIdAndCustomSelectSql(user.getId()));
}这种List遍历,每一次set都会查询一次数据库,上面一条执行完了才能执行下一条,用多线程优化这个过程,怎样可以让五条同步执行?
比如你上面这个循环,是拿每个 userId 去查一次,这样查多次,为什么不先在Java层拿到所有IdList , 然后通过一个 SQL 去查询到结果集呢
loop start
--> 查询id对应的值(发送数据库请求,高I/O操作)
--> 保存值的数据
loop end显然,loop了多少次,你的高IO请求就做了多少次。
可以优化的场景是降低发起高IO请求的次数,做批量处理id集合切分(50个id一个批次)
loop start
--> 查询50个id的值(发送数据库请求,高I/O操作)
--> 保存50个值的数据
loop end高IO的请求次数就降低为原有的1/50,实际上集合大小可控的话,完全可以不做循环一次查询出来。
应该是先返回列表,客户端点击再返回详情。
建议从自身业务需求入手,重新设计,无论是复杂的代码还是复杂的sql,都不是设计的捷径
String yy = this.XXXService.getByIdAndCustomSelectSql(user.getId());
user.setA(yy);
user.setB(yy);
user.setC(yy);
user.setD(yy);
user.setE(yy);
}