整体架构
overall.png执行流程
process.png定时任务和执行引擎
- 针对单个线程,将HttpClient修改成单例。
- 针对多线程采用ThreadLocal拷贝HttpClient实例。
- 在做耗时较长(相对而言)的Http请求交互的时候,重新生成一个httpClient对象,而不是用类变量httpclient进行管理一个线程的所有http请求。
- 数据表更新操作采用异步方法。
代码样例
-
定时线程池
@Bean public ScheduledExecutorFactoryBean suiteExecutorFactoryBean() { ScheduledExecutorFactoryBean executorFactoryBean = new ScheduledExecutorFactoryBean(); executorFactoryBean.setThreadNamePrefix("monitor_thread_pool"); executorFactoryBean.setPoolSize(10); return executorFactoryBean; }
-
类静态变量HttpClient
private static ThreadLocal<CloseableHttpClient> httpClient = new ThreadLocal<CloseableHttpClient>() { @Override public CloseableHttpClient initialValue() { RequestConfig config = RequestConfig.custom() .setSocketTimeout(10000) .setConnectTimeout(10000) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(100); HttpClientBuilder builder = HttpClients.custom(); builder.setDefaultRequestConfig(config).setConnectionManager(cm); return builder.build(); } };
-
重试机制
// 如果重试,新建httpClient if (isRetry) { httpClientInstance = createHttpClient(); } else { httpClientInstance = httpClient.get(); }
-
异步方式更新数据表
// 使用异步方式更新数据表 final int finalResultCode = resultCode; final String finalOptResponseBody = finalResponseBody; final int finalFailedTime = failedTime; scheduledExecutorService.submit(new Runnable() { @Override public void run() { //最后更新服务接口表 service.setState(finalResultCode); service.setResponseBody(finalOptResponseBody); service.setSampleTime(new Date()); service.setFailedTime(finalFailedTime); serviceDao.save(service); } });
网友评论