java实现:轮询web服务

java实现:轮询web服务,java,web-services,algorithm,jakarta-ee,webservice-client,Java,Web Services,Algorithm,Jakarta Ee,Webservice Client,请找到以下我的要求 要求:轮询web服务。在属性文件中配置了轮询最大超时、轮询间隔这两个关键参数。总体目标是花费一段时间来获得响应。如果我们得到的响应具有in max_timeout,那么我们可以将响应返回给客户机。否则,我们将抛出一个错误,说明操作不成功 下面是我编写的代码片段 int maxTimeOut = 10; int interval = 2; int iterations = maxTimeOut/interval; boolean success = false; for

请找到以下我的要求

要求:轮询web服务。在属性文件中配置了轮询最大超时、轮询间隔这两个关键参数。总体目标是花费一段时间来获得响应。如果我们得到的响应具有in max_timeout,那么我们可以将响应返回给客户机。否则,我们将抛出一个错误,说明操作不成功

下面是我编写的代码片段

int maxTimeOut = 10;
int interval   = 2;

int iterations = maxTimeOut/interval;
boolean success = false;

for (int i = 0; i < iterations; i++)
{
    System.out.println("Number of iteration = " + i);
    try
    {
        Thread.sleep(interval * 1000);
        System.out.println("Waited for " + interval + " seconds");

        success =  getWSResponse(i);
        System.out.println("CALL" + ((success) ? "SUCCESSFUL" : "FAIL"));

        if(success) break;

    }catch (InterruptedException ie)
    {
        System.out.println(ie.getMessage());
    }
}

//Send the success flag to client
int maxTimeOut=10;
整数区间=2;
int迭代次数=最大超时/间隔;
布尔成功=假;
对于(int i=0;i

你能告诉我这是否是正确的投票方式吗。我有点担心这段代码假设webservice调用会立即返回。如果这需要2-3秒(通常是这样),那么单是轮询就需要花费超过max_超时的时间。我们怎样才能解决这个问题。有比这更好的方法吗。

如果轮询仅仅意味着Web服务已启动并正在运行,那么在轮询代码中,您可以尝试打开与Web服务的连接(连接超时)。如果您能够成功连接,这意味着Web服务已启动

HttpURLConnection connection = null;
URL url = new URL("URL");
connection = (HttpURLConnection) url.openConnection();
connection .setConnectTimeout(timeout);//specify the timeout and catch the IOexception
connection.connect();
编辑

或者,您可以在有超时的任务中使用executor(请参见java.util.concurrent.ExecutorService)调用webservice,并做出相应的决定。样本:

// Make the ws work a time-boxed task
            final Future<Boolean> future= executor.submit(new Callable<Boolean>() {         
                @Override
                public Boolean call() throws Exception {
                    // get ws result
                       return getWSResponse();
                }
            });
try {
                boolean result = future.get(max_wait_time, TimeUnit.SECONDS);
            } catch (TimeoutException te) {
throw e;
}
//使ws工作为时间限制任务
final Future=executor.submit(new Callable(){
@凌驾
公共布尔调用()引发异常{
//获取ws结果
返回getWSResponse();
}
});
试一试{
布尔结果=future.get(最大等待时间,时间单位为秒);
}捕获(TimeoutException te){
投掷e;
}

您可以将
ScheduledExecutorService
的使用与
HttpURLConnection
结合使用,在给定延迟内轮询超时,如果需要更长时间,则中止任务。

Nrj,我们必须实际调用web服务上返回大xml的方法,我们需要对其进行解析,然后确定响应是“success”还是“inprogress”。整个过程都在上面的getWSResponse调用中抽象。我们的目标不仅仅是检查连接。在控制器类中使用未来的代码而不锁定它是否可以?谢谢。您能否传递正确描述此场景的示例代码/url。顺便说一句,您是否看到我附加的代码片段有任何问题(除了我指定的问题之外),您的代码的一个问题是中断。因为您不传播中断标志或抛出中断异常。
catch(InterruptedException ie){System.out.println(ie.getMessage());}
。。。不要那样做。只需重新播放
{throw new RuntimeException(ie)}
谢谢artbristol的建议。我会将此代码更改为抛出RTE而不是SOP。