Spring Boot using multiple threads execute sql statement

1. Submit sql method respectively using submitSql Controller layer, getResult method to obtain thread execution results

dataService.submitSql(uuid,endsql);
return dataService.getResult(uuid);

endsql for the sql statement to be executed, uuid is uniquely identifies the entry thread information.

2. Information Service layer defines the thread pool, and a method in a multithreaded execution.

  2.1 Definitions thread pool information and the results format.

 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 realization method

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 statement submitted to the task

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 The method of obtaining the results of

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;
}

 

Published 36 original articles · won praise 19 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_27182767/article/details/105044631