Moh*_*itt 2 java lambda design-patterns java-8
我有两个类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
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我需要提供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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
只需要一个Callable参数:
public static <R> R retry(Callable<R> action) {
// Retry logic
while(/* retry condition */) {
action.call();
}
}
Run Code Online (Sandbox Code Playgroud)
并这样称呼它:
Retry.retry(() -> a.fetchMax());
Retry.retry(() -> b.fetchPercentile(200));
Run Code Online (Sandbox Code Playgroud)
你可能想要使用guava-retrying来获取灵感,这是Google的Guava库的一个小扩展,允许创建可配置的重试策略(免责声明:我是原作者).
| 归档时间: |
|
| 查看次数: |
230 次 |
| 最近记录: |