1.在Controller层中分别使用submitSql方法提交sql,getResult方法获取线程执行结果
dataService.submitSql(uuid,endsql);
return dataService.getResult(uuid);
endsql为要执行的sql语句,uuid为唯一标识该条线程信息。
2.在Service层定义线程池的信息,和多线程执行的方法。
2.1定义线程池信息和执行结果格式。
public static ThreadPoolExecutor executor = new ThreadPoolExecutor(5,10, 5,TimeUnit.MINUTES,new ArrayBlockingQueue<>(5));
public static HashMap<String, Future<List<LinkedHashMap<String, Object>>>> resultList = new HashMap<String, Future<List<LinkedHashMap<String, Object>>>>();
2.2实现Callable方法
public static class SqlTask implements Callable<List<LinkedHashMap<String, Object>>> {
private String sql;
private DataMapper dataMapper;
public SqlTask(String sql, DataMapper dataMapper) {
this.sql=sql;
this.dataMapper=dataMapper;
}
@Override
public List<LinkedHashMap<String, Object>> call() throws Exception{
DBIdentifier.setProjectCode(projectCode);
List<LinkedHashMap<String,Object>> res=dataMapper.getPublicItems(sql);
System.out.println("处理sql:"+sql);
return res;
}
}
2.3提交执行sql语句任务
public void submitSql(String uuid,String sql){
Future<List<LinkedHashMap<String, Object>>> result = executor.submit(new SqlTask(sql,dataMapper));
resultList.put(uuid,result);
}
2.4获取执行结果方法
public CloudwalkResult getResult(String uuid) throws InterruptedException {
Future f = resultList.get(uuid);
if(f!=null){
while(!f.isDone()){
Thread.sleep(100);
System.out.println("还没有执行完....");
}
System.out.println("执行完毕");
List<LinkedHashMap<String, Object>> r = null;
try {
r = (List<LinkedHashMap<String, Object>>) f.get();
resultList.remove(uuid);
} catch (Exception e) {
return CloudwalkResult.fail("1",e.getMessage());
}
return CloudwalkResult.success(r);
}else{
System.out.println("任务不存在");
}
return null;
}