2016-07-06 77 views
0

我有以下使用代理服务器的方法。该代理有时会抛出错误,我希望该方法重新尝试一个代理错误。我试图通过使用jcabi-aspects库来做到这一点,但它似乎并没有做到它应该做的。我没有看到有关故障的详细消息。任何帮助实现这一点表示赞赏。错误重试方法

@RetryOnFailure(attempts = 2, verbose = true) 
public String update(String lastActivityDate) 
{ 
    StringBuffer response = new StringBuffer(); 

    try 
    { 
     String url = "https://api.somesite.com/updates"; 
     URL urlObj = new URL(url); 
     HttpsURLConnection con = null; 
     if (useProxy) 
     { 
      myapp.Proxy proxyCustom = getRandomProxy(); 
      Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyCustom.getProxyIp(), proxyCustom.getProxyPort())); 
      con = (HttpsURLConnection) urlObj.openConnection(proxy); 
     } 
     else 
     { 
      con = (HttpsURLConnection) urlObj.openConnection(); 
     } 

     // add reuqest header 
     con.setRequestMethod("POST"); 
     con.setRequestProperty("User-Agent", USER_AGENT); 
     con.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 
     con.setRequestProperty("host", urlObj.getHost()); 
     con.setRequestProperty("Connection", "Keep-Alive"); 

     String urlParameters = "{}"; 

     // Send post request 
     con.setDoOutput(true); 
     DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
     wr.writeBytes(urlParameters); 
     wr.flush(); 
     wr.close(); 

     int responseCode = con.getResponseCode(); 
     // System.out.println("\nSending 'POST' request to URL : " + url); 
     // System.out.println("Post parameters : " + urlParameters); 
     // System.out.println("Response Code : " + responseCode); 

     BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
     String inputLine; 

     while ((inputLine = in.readLine()) != null) 
     { 
      response.append(inputLine); 
     } 
     in.close(); 

     // print result 
     // System.out.println(response.toString()); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 

    return response.toString(); 
} 

回答

1

发生这种情况是因为您不应该尝试捕捉方法。该注释:@RetryOnFailure(attempts = 2, verbose = true)将执行您的方法,如果它抛出一个exeption。但是,您将所有代码封装在try catch块中。

望着documentation

注解你的方法与@RetryOnFailure注释,并在方法 异常的情况下,它的执行将被重复几次:

你也可能想在重试之间添加一个延迟:@RetryOnFailure(attempts = 2, delay = 2000, verbose = true)(默认值是以毫秒为单位)

编辑:如果你不想配置它与jcabi一起工作,那么你可以做这样的事情:

int retries = 0; 
Boolean success = false; 
while(retries <x && ! success){ // you need to set x depending on how many retries you want 
    try{ 
     // your code goes here 
     success = true; 
    } 
    catch{ 
     retries++; 
    } 
} 
+0

所以我会替换try-catch块抛出异常在方法?公共字符串更新(字符串lastActivityDate)抛出异常 这应该工作正确吗? – Arya

+0

@雅莉是的,应该这样做。只要确保使用此方法的代码在函数失败3次时就会抛出错误。编辑:不确定是否会抛出3例外,如果所有的尝试失败或只是1例外。 – limbo

+0

看起来像是需要更多的设置,然后将jcabi-aspects依赖项添加到pom.xml。从我阅读的内容来看,这听起来像是我需要设置二进制编织才能使其工作。我对吗? – Arya