You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Web服务provideULDinformation设置1秒超时并返回null?

实现Web服务调用1秒超时返回null的方案

要实现Web服务provideULDinformation调用1秒未响应就返回null的需求,我们可以借助Java的ExecutorService和Future来实现异步调用并设置超时时间。下面是修改后的完整代码,同时附上关键逻辑的解释:

public String getUldState(String uldNumber) throws SystemException {
    ProvideULDinformationRequest wsRequest = new ProvideULDinformationRequest();
    wsRequest.setIdcode(uldNumber);
    
    // 创建单线程线程池用于执行异步调用
    ExecutorService executor = Executors.newSingleThreadExecutor();
    try {
        // 将Web服务调用逻辑封装为Callable任务
        Callable<ProvideULDinformationResponse> callable = () -> {
            try {
                return service.provideULDinformation(wsRequest);
            } catch (ProvideULDinformationBusinessException e) {
                e.printStackTrace();
                return null;
            }
        };
        
        // 提交任务并设置1秒超时时间
        Future<ProvideULDinformationResponse> future = executor.submit(callable);
        ProvideULDinformationResponse uldInfo = future.get(1, TimeUnit.SECONDS);
        
        if (uldInfo != null) {
            return uldInfo.getUldPhysicalStatus();
        }
    } catch (TimeoutException e) {
        // 捕获超时异常,直接返回null
        return null;
    } catch (InterruptedException e) {
        // 处理线程中断,恢复中断状态并包装为SystemException抛出
        Thread.currentThread().interrupt();
        throw new SystemException("线程被中断", e);
    } catch (ExecutionException e) {
        // 处理Callable内部抛出的其他异常
        throw new SystemException("服务调用执行异常", e.getCause());
    } finally {
        // 关闭线程池,释放资源
        executor.shutdown();
    }
    return null;
}

关键逻辑说明

  • 异步任务封装:把Web服务的同步调用逻辑放到Callable中,交给ExecutorService异步执行,这样我们可以对这个任务设置超时时间。
  • 超时控制:通过Future.get(1, TimeUnit.SECONDS)指定如果1秒内任务没有完成,就抛出TimeoutException,此时我们直接返回null。
  • 异常处理:
    • 保留了原代码中对ProvideULDinformationBusinessException的处理;
    • 处理线程中断异常InterruptedException,恢复线程中断状态并包装为SystemException抛出;
    • 处理ExecutionException,这是Callable内部抛出的异常被包装后的类型,我们需要取出实际异常重新抛出。
  • 资源释放:在finally块中关闭线程池,避免线程资源泄漏。

内容的提问来源于stack exchange,提问作者R.Walid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:38:36