java 给某段代码加超时限制

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();
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_40841731/article/details/131090314