如何为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
相关产品推荐
相关产品推荐

