1 // 创建查询任务 2 List<ProbeQueryTask> tasks = ReportQueryHelper.buildTasks(apiParams, headerMap); 3 List<JSONObject> results = TaskThreadPoolExecutor.submitTask(tasks);
1 1 // 创建任务列表 2 2 public static List<ProbeQueryTask> buildTasks(List<ApiParameter> apiParams, Map<String, String> headerMap) { 3 3 ArrayList<ProbeQueryTask> tasks = new ArrayList<>(); 4 4 for (ApiParameter apiParam : apiParams) { 5 5 ProbeQueryTask task = new ProbeQueryTask(apiParam, headerMap); 6 6 tasks.add(task); 7 7 } 8 8 return tasks; 9 9 }
1 package com.-.it.regioc.task; 2 3 import com.alibaba.fastjson.JSONObject; 4 import com.-.it.regioc.bean.apiconfig.ApiParameter; 5 import com.-.it.regioc.utils.HttpUtils; 6 import lombok.extern.slf4j.Slf4j; 7 import java.io.IOException; 8 import java.util.Map; 9 import java.util.concurrent.Callable; 10 11 @Slf4j 12 public class ProbeQueryTask implements Callable<JSONObject> { 13 private final ApiParameter param; 14 private final Map<String, String> header; 15 16 public ProbeQueryTask(ApiParameter param, Map<String, String> header) { 17 this.param = param; 18 this.header = header; 19 } 20 21 private JSONObject execute() { 22 String url = param.getRequestUrl(); 23 Object data = param.getRequestData(); 24 String requestData = null; 25 if (data != null) { 26 requestData = JSONObject.toJSONString(data); 27 } 28 JSONObject result = null; 29 try { 30 String resultStr = HttpUtils.postRequest(url, requestData, header); 31 result = JSONObject.parseObject(resultStr); 32 result.put("topic", param.getTopic()); 33 result.put("stage", param.getStage()); 34 result.put("apiName", param.getApiName()); 35 result.put("probeId", param.getProbeId()); 36 } catch (IOException e) { 37 log.error("探针查询异常:{}", param, e); 38 } 39 return result; 40 } 41 42 @Override 43 public JSONObject call() { 44 return execute(); 45 } 46 47 public ApiParameter getParam() { 48 return param; 49 } 50 }
1 package com.-.it.regioc.task; 2 3 import com.alibaba.fastjson.JSONObject; 4 import lombok.extern.slf4j.Slf4j; 5 import java.util.ArrayList; 6 import java.util.List; 7 import java.util.concurrent.*; 8 9 @Slf4j 10 public class TaskThreadPoolExecutor { 11 private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 12, 1, TimeUnit.MINUTES, new ArrayBlockingQueue<>(150)); 12 13 /** 14 * 提交任务 15 */ 16 public static <T extends Callable<JSONObject>> List<JSONObject> submitTask(List<T> tasks) { 17 ArrayList<Future<JSONObject>> futures = new ArrayList<>(); 18 for (T task : tasks) { 19 Future<JSONObject> future = executor.submit(task); 20 futures.add(future); 21 } 22 List<JSONObject> results = new ArrayList<>(); 23 for (int i = 0; i < futures.size(); i++) { 24 try { 25 JSONObject result = futures.get(i).get(); 26 results.add(result); 27 } catch (Exception e) { 28 log.error("线程池查询探针异常:{}", tasks.get(i), e); 29 } 30 } 31 return results; 32 } 33 }
标签:tasks,ProbeQueryTask,JSONObject,List,param,result,import From: https://www.cnblogs.com/mingruifeng/p/16904881.html