Mysql支持的索引类型:B-TREE索引与HASH索引
为什么要用索引?
- 使用索引后减少了存储引擎需要扫描的数据量,加快查询速度
- 索引可以把随机I/O变为顺序I/O
- 索引可以帮助我们对所搜结果进行排序以避免使用磁盘临时表
alter table user_score add index `un_org_category_business` (`org_code`,`category_id`,`business_id`,`business_type`) USING BTREE;BTREE索引
B-TREE索引的特点
- B-TREE以B+树结构存储数据,大大加快了数据的查询速度
- B-TREE索引在范围查找的SQL语句中更加适合(顺序存储)
使用场景
- 全值匹配的查询SQL,如 where act_id= '1111_act'
- 联合索引汇中匹配到最左前缀查询,如联合索引 KEY idx_actid_name(act_id,act_name) USING BTREE,只要条件中使用到了联合索引的第一列,就会用到该索引,但如果查询使用到的是联合索引的第二列act_name,该SQL则便无法使用到该联合索引(注:覆盖索引除外)
- 匹配模糊查询的前匹配,如where act_name like '11_act%'
- 匹配范围值的SQL查询,如where act_date > '9865123547215'(not in和<>无法使用索引)
- 覆盖索引的SQL查询,就是说select出来的字段都建立了索引
使用多线程调用,并且要获取返回值,这种场景使用java8中的CompleteFuture非常合适。
代码调整为:
CompletableFuture[] futureArray = dataList.stream()
.map(data -> CompletableFuture
.supplyAsync(() -> query(data), asyncExecutor)
.whenComplete((result, th) -> {
})).toArray(CompletableFuture[]::new);
CompletableFuture.allOf(futureArray).join();
CompleteFuture的本质是创建线程执行,为了避免产生太多的线程,所以使用线程池是非常有必要的。
优先推荐使用ThreadPoolExecutor类,我们自定义线程池。
具体代码如下:
ExecutorService threadPool = new ThreadPoolExecutor(
8, //corePoolSize线程池中核心线程数
10, //maximumPoolSize 线程池中最大线程数
60, //线程池中线程的最大空闲时间,超过这个时间空闲线程将被回收
TimeUnit.SECONDS,//时间单位
new ArrayBlockingQueue(500), //队列
new ThreadPoolExecutor.CallerRunsPolicy()); //拒绝策略
也可以使用ThreadPoolTaskExecutor类创建线程池:
@Configuration
public class ThreadPoolConfig {
private int corePoolSize = 8;
private int maxPoolSize = 10;
private int keepAliveSeconds = 60;
private int queueCapacity = 1;
private boolean allowCoreThreadTimeOut = false;
@Bean("asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setAllowCoreThreadTimeOut(allowCoreThreadTimeOut);
// 设置拒绝策略,直接在execute方法的调用线程中运行被拒绝的任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 执行初始化
executor.initialize();
return executor;
}
}
限制一次性查询的记录条数
分页
需要业务系统的前端做分页功能,同时后端接口要调整支持分页查询。
分批调用接口如果那5批调用评价查询接口的操作,是在for循环中单线程顺序的,整体耗时当然可能会变慢。
但业务系统也可以改成多线程调用,只需最终汇总结果即可。
参考:https://mp.weixin.qq.com/s/8sxe26ozba6IQBeMmA-oDg



