Javaメソッドにタイムアウトを設定

2021 ワード

package com.sfpay.console.util;

......
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
......

/**
 *    :
* Handler *

* :
* Common Util *

* @author 80003614 * CreateDate: 2018-12-3 */ @Component("dataExtrComHandler") public class DataExtrComHandler { ...... /** * sql , * @param connection * @param querySql sql * @return * @throws Exception */ public List executeDBQuery(final Connection connection, final String querySql) throws Exception { // , 。 // ArrayListHandler: , Object , List ExecutorService executor = Executors.newSingleThreadExecutor(); FutureTask> future = new FutureTask>(new Callable>() { @Override public List call() throws Exception {// sql QueryRunner queryRunner = new QueryRunner(); List data = queryRunner.query(connection, querySql, new ArrayListHandler()); // Thread.sleep(11000); return data; } }); String exeSqlTimeout = null; try { executor.execute(future); // query timeout //exeSqlTimeout = sysParaCfgMapper.selectParaValue("EXE-SQL-TIMEOUT-DURATION"); List result = future.get(1000*60, TimeUnit.MILLISECONDS); return result; } catch (TimeoutException e) { // sql throw new TimeoutException( "Sql ! Sql " + (Long.parseLong(exeSqlTimeout) / 1000 / 60) + " ..."); } catch (Exception e) { throw new RuntimeException("Sql :" + e.getMessage()); } finally { future.cancel(true); executor.shutdown(); } } ...... }

ソース:https://blog.csdn.net/ithouse/article/details/78257418