如果webservice在1秒内没有响应,则返回null,然后返回null

时间:2018-05-28 14:54:49

标签: java multithreading web-services java-ee timeout

table

如果网络服务 provideULDinformation 在一秒钟后没有响应,我想返回null。

1 个答案:

答案 0 :(得分:0)

单向是使用CompletableFuture<>来执行超时。

首先将您的实际代码包装到私有方法:

private String getUldStatePrivate(String uldNumber) throws SystemException {
    ProvideULDinformationRequest wsRequest = new ProvideULDinformationRequest();
    wsRequest.setIdcode(uldNumber);
    ProvideULDinformationResponse uldInfo = null;
    try {
        uldInfo = service.provideULDinformation(wsRequest);
    } catch (ProvideULDinformationBusinessException e) {
        e.printStackTrace();
    } 
    if (uldInfo != null) {
        return uldInfo.getUldPhysicalStatus();      
    }       
    return null;
}

然后从您的控制器中调用它:

public String getUldState(String uldNumber) {
    CompletableFuture<String> response = CompletableFuture.supplyAsync(() -> getUldStatePrivate(uldNumber));

    try {
        return response.get(1, TimeUnit.SECONDS);
    } catch(TimeoutException ex) {
        // timeout, log error, return
        return null
    }
}

在Java 7中,您可以使用普通FutureTask

ExecutorService pool = Executors.newFixedThreadPool(10);

public String getUldState(String uldNumber) {
    FutureTask<String> response = new FutureTask<>(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return getUldStatePrivate(uldNumber);
        }
    });
    pool.execute(response);

    try {
        return response.get(1, TimeUnit.SECONDS);
    } catch(TimeoutException ex) {
        // timeout, log error, return
        return null
    }
}