Last active
January 22, 2021 13:21
-
-
Save pfrozi/0fe481b98926af607648c9ccea0705bb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.jasongoodwin.monads.Try; | |
import org.apache.log4j.Logger; | |
import java.util.function.Function; | |
public abstract class Retrier<Tin, Tout> { | |
private static Logger logger = Logger.getLogger(WsExecuter.class); | |
private int LIMIT_OF_RETRIES; | |
protected abstract Function<Tin,Tout> executeRequest(); | |
public Function<Tin,Tout> execute() { | |
return in-> Try.ofFailable(() -> executeRequest().apply(in)).recover(retry(in)); | |
} | |
private Function<Throwable, Tout> retry(Tin in) { | |
return throwable -> { | |
for (int i = 0; i < LIMIT_OF_RETRIES; i++) { | |
Try<Tout> responseTry = Try.ofFailable(()->executeRequest().apply(in)) | |
.onFailure(error -> logger.error("Error occurs: " + error.getMessage())); | |
if (responseTry.isSuccess()) return responseTry.getUnchecked(); | |
} | |
throw new LimitOfRetriesException(); | |
}; | |
} | |
} | |
// extends | |
public class TestRetrier extends Retrier<RequestModel, ResponseModel> { | |
public LogonExecuter(TestService testService) { | |
this.testService = testService; | |
} | |
@Override | |
protected Function<RequestModel, ResponseModel> executeRequest(){ | |
return requestModel -> foo(requestModel); | |
} | |
} | |
// Use | |
public class Executer { | |
private TestRetrier testRetrier; | |
public LogonResponseModel send(RequestModel request){ | |
return testRetrier.execute().apply(request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment