如何编写java客户端代码以重试Java Webservice

时间:2012-09-05 17:41:41

标签: java web-services

我必须为其他一方发布的web服务编写Java客户端代码。 在该客户端代码中,如果发生任何超时,我必须为指定的次数提供重试选项。

在webservice调用中,我已经传递了非持久化对象,因此在重试过程中我认为这些 对象应该保存。

代码示例非常有用。

2 个答案:

答案 0 :(得分:5)

AOP和Java注释是正确的方法。我会推荐jcabi-aspects(我是开发人员)的读取机制:

import com.jcabi.aspects.RetryOnFailure;
@RetryOnFailure(attempts = 4)
public String load(URL url) {
  // sensitive operation that may throw an exception
  return url.openConnection().getContent();
}

答案 1 :(得分:0)

这应该可以帮助您入门(但绝对不是生产质量)。实际的webservice调用应该在一个实现Callable<T>的类中,其中T是Web服务期望的响应类型。

import java.util.List;
import java.util.concurrent.Callable;

public class RetryHelper<T>
{
    // Number of times to retry before giving up.
    private int numTries;

    // Delay between retries.
    private long delay;

    // The actual callable that call the webservice and returns the response object.
    private Callable<T> callable;

    // List of exceptions expected that should result in a null response 
    // being returned.
    private List<Class<? extends Exception>> allowedExceptions;

    public RetryHelper(
        int numTries,
        long delay,
        Callable<T> callable,
        List<Class<? extends Exception>> allowedExceptions)
    {
        this.numTries = numTries;
        this.delay = delay;
        this.callable = callable;
        this.allowedExceptions = allowedExceptions;
    }

    public T run()
    {
        int count = 0;
        while (count < numTries)
        {
            try
            {
                return callable.call();
            }
            catch (Exception e)
            {
                if (allowedExceptions.contains(e.getClass()))
                {
                    return null;
                }
            }
            count++;
            try
            {
                Thread.sleep(delay);
            }
            catch (InterruptedException ie)
            {
               // Ignore this for now.
            }
        }
        return null;
    }
}