2012-01-23 69 views
2

请在下面找到我的要求。java实现:轮询web服务

要求:轮询Web服务。属性文件中配置了两个关键的轮询参数max_timeout,polling_interval。总体目标是花费整体时间获得回应。如果我们在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 

如果这是轮询的正确实施,你能纠正我吗?我有点担心这段代码假设web服务调用很快返回。如果这需要2-3秒(通常是这样),那么我们将单独花费超过max_timeout。我们如何解决这个问题。有没有比这更好的方法。

+1

'catch(InterruptedException ie){System.out.println(ie.getMessage()); }'不要那样做。只需重新抛出它{{抛出新的RuntimeException(ie)}' – artbristol

+0

感谢artbristol为您的建议。我将使此代码更改为抛出RTE而不是SOP。 –

回答

1

如果轮询仅表示web服务已启动并正在运行,则在您的轮询代码中,您可以尝试打开与webservice的连接(连接超时)。如果您能够成功连接,则表示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(); 

编辑

或者,你可以调用使用执行人的Web服务(见java.util.concurrent.ExecutorService中)与超时任务,并可以相应地决定。示例:

// 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; 
} 
+0

Nrj,我们必须实际调用Web服务的方法来返回大的xml,我们需要解析它,然后我们找出响应是“成功”还是“进行中”。整个事件在上面的getWSResponse **调用中被抽象出来。目的不在于检查连通性。 –

+1

看我的编辑。这应该有助于 – Nrj

+0

感谢Nrj的代码片段。让我试试看。 –

2

你可以结合与HttpURLConnection -Timeout使用ScheduledExecutorService在一个给定的延迟轮询 - 和中止任务,如果它需要任何更长的时间。

+0

谢谢光。您可以传递正确描述此场景的示例代码/网址吗?顺便说一句,你看到任何问题与我附加的代码片段(除了我指定的问题) –

+1

你的代码的一个问题将是中断。由于您不传播中断标志或抛出中断的异常。 –