Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrying Method calls in generic way

My Java application requires a retry logic on remote calls failures. These remote calls are:

  • scattered all over the application
  • pertain to different Remote Service classes.

Also, the retry logic may have varying retry interval and varying retry attempts.

I need a generic retry() implementation which can make appropriate method calls depending on from where it is called. Below is a simple code illustration of I am looking for. I know we can attempt to do this using java reflection, but, is there a framework or an open source available somewhere which is read-to-use?

try {
 ClassA objA = remoteServiceA.call(paramA1, paramA2, ...);
} catch (Exception e){
 ClassA objA = (ClassA)retry(remoteService, listOfParams, ..); // generic method call
}
..

try {
 ClassB objB = remoteServiceB.call(paramB1, paramB2, ...);
} catch (Exception e){
 ClassA objB = (ClassB)retry(remoteService, listOfParams, ..); // generic method call
}
like image 724
a-sak Avatar asked Jun 06 '12 20:06

a-sak


People also ask

How do you retry a function call in Java?

A simple solution to implement retry logic in Java is to write your code inside a for loop that executes the specified number of times (the maximum retry value).

What is a retry logic?

Configurable Retry Logic is an eCommerce platform feature that recovers failed transactions due to soft declines.

What is retry in Microservices?

In a microservices architecture, the retry pattern is a common pattern for recovering from transient errors. Some examples of these errors are: Network failure. An application lost connectivity for a short period of time.


1 Answers

As already suggested, you should use AOP and Java annotations. I would recommend a read-made mechanism from jcabi-aspects (I'm a developer):

@RetryOnFailure(attempts = 3, delay = 5)
public String load(URL url) {
  return url.openConnection().getContent();
}

Read also this blog post: http://www.yegor256.com/2014/08/15/retry-java-method-on-exception.html

Update: Check RetryFunc from Cactoos.

like image 160
yegor256 Avatar answered Sep 29 '22 00:09

yegor256