1、需求场景:本项目中请求sftp拿文件的时候,有时候各种原因连不上,导致超时。但接口等待超时异常会很久。我们需要自定义时间范围内返回异常。
private byte[] getSftpFile(String path){
ExecutorService exec = Executors.newFixedThreadPool(1);
Callable<byte[]> call = new Callable<byte[]>() {
@Override
public byte[] call() throws Exception {
//具体业务代码
return getByteFile(path);
}
};
try {
Future<byte[]> future = exec.submit(call);
byte[] ret = future.get(10000 * 1, TimeUnit.MILLISECONDS); // 任务处理超时时间设为 10 秒
return ret;
} catch (TimeoutException e) {
e.printStackTrace();
throw new CommonException("sftp服务器异常!");
} catch (Exception e) {
e.printStackTrace();
throw new CommonException("sftp服务器异常!");
} finally {
exec.shutdown();
}
}