问题
之前的老项目里面有调用行云接口做一些操作(使用行云的SDK),但是行云接口经常性地不返回数据,也不报超时异常,整个程序就卡死在哪里不动了。
解决方案
为了解决这个问题,我们需要对调用行云的方法进行超时限制,这样只要这个方法超时,那就直接报超时异常,结束程序并进行后面的操作。
实现代码
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
Callable<返回值类型> call = () -> 调用行云接口的方法(参数列表);
try {
Future<返回值类型> future = poolExecutor.submit(call);
返回值 = future.get(方法超时秒数, TimeUnit.SECONDS);
} catch (TimeoutException e) {
log.error("订单号:{},请求行云超时", 订单号);
} catch (InterruptedException | ExecutionException e) {
log.error("订单号:{},请求行云异常", 订单号, e);
} finally {
poolExecutor.shutdown();
try {
poolExecutor.awaitTermination(线程超时秒数, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
网友评论