3

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

在 web 服务调用中我传递了非持久对象,所以在重试过程中我认为应该保存这些对象。

代码示例将非常有帮助。

4

2 回答 2

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();
}
于 2013-02-03T08:36:18.700 回答
0

这应该可以帮助您入门(但绝对不是生产质量)。实际的 web 服务调用应该在一个类中,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;
    }
}
于 2012-09-05T17:54:32.317 回答