我有两个课程A
& B
,就像这样:
class A {
public Integer fetchMax() {
// Make a network call & return result
}
}
class B {
public Double fetchPercentile(Integer input) {
// Make a network call & return result
}
}
现在我需要为两种方法retry
&提供fetchMax()
机制。 fetchPercentile(Integer)
。我想使用helper
类来提供此行为,其中retry
方法可以使用instance
(A或B),method-name
和method-arguments
。重试基本上会对提供的对象方法进行重新尝试。
这样的事情:
class Retry {
public static R retry(T obj, Function<T, R> method, Object... arguments) {
// Retry logic
while(/* retry condition */)
{
obj.method(arguments);
}
}
}
答案 0 :(得分:8)
只需要Callable
作为参数:
public static <R> R retry(Callable<R> action) {
// Retry logic
while(/* retry condition */) {
action.call();
}
}
并以这种方式称呼它:
Retry.retry(() -> a.fetchMax());
Retry.retry(() -> b.fetchPercentile(200));
您可能希望使用guava-retrying作为Google Guava library的一个小扩展程序来获取灵感,以便创建可配置的重试策略(免责声明:I&#39; m原作者)。