14 Ocak 2020 Salı

SpringRetry RetryTemplate Sınıfı

Giriş
Şu satırı dahil ederiz. 
import org.springframework.retry.support.RetryTemplate;
- RetryOperations arayüzünden kalıtır. Bu arayüzün 4 tane overload edilmiş execute() metodu var. Bu metodlar parametre olarak RetryCallback, RecoveryCallback, RetryState nesneler alırlar.
RetryCallback yapılması istenen işi temsil eder.

- Bu sınıfı bir bean yapmak iyi bir fikir olabilir.

Stateless retry interceptor
Açıklaması şöyle. Yani thread'i bloke eder
... all retry attempts happen without exiting the interceptor call, so the interceptor is called only once regardless of the number of retries. Any required state (e.g. number of attempts) is kept on the stack.
Stateful retry interceptor
Açıklaması şöyle. Yani thread'i bloke etmez
Spring Retry also provides a stateful retry interceptor in which case the Exception is propagated outside of the interceptor. In other words the interceptor is called once per retry, therefore it needs to somehow remember the state of the retries (hence it is called stateful). The main use case for a stateful retry interceptor is so that it can be used in Hibernate transactions (through the Spring @Transactional interceptor), where if the Hibernate Session throws an exception, the transaction must be rolled back and the Session discarded. This means that upon failure the call has to exit the retry interceptor, so that the transaction interceptor can close the session and open a new one for each retry attempt.
execute metodu - RetryCallback
RetryCallback exception fırlatırsa backoffpolicy ve retrypolicy müsaade ediyorsa, tekrar çalıştırılır.

RetryCallback sınıfının doWithRetry() metodu RetryContext parametresi alır. Açıklaması şöyle
The method parameter for the RetryCallback is a RetryContext. Many callbacks ignore the context. However, if necessary, you can use it as an attribute bag to store data for the duration of the iteration.

A RetryContext has a parent context if there is a nested retry in progress in the same thread. The parent context is occasionally useful for storing data that needs to be shared between calls to execute.
Örnek - lambda
Şöyle yaparız
retryTemplate.execute(arg -> callMyFunction());
Örnek
Şöyle yaparız.
public Object getSomething(@PathVariable("id") String id) throws Exception{

  return retryTemplate.execute(new RetryCallback<Object, Exception>() {
    @Override
    public Object doWithRetry(RetryContext arg0) {
      Object o = restTutorialClient.getEmployeesList(id);
      return o;
    }
});
Örnek
RetryCallback arayüzü yerine lambda kullanmak için şöyle yaparız.
@Service
public class TestService {

  @Autowired
  private RetryTemplate retryTemplate;

  public String testService() {

    //Retryable
    String result = retryTemplate.execute(context -> {
      System.out.println("Inside the Method, Retry = " + context.getRetryCount());
      if (context.getRetryCount() == 0)
        throw new RuntimeException("Something went wrong");
      return "Successfully Completed";
    });

    //Result
    System.out.println("FINAL Result = " + result);
    return result;
  }
}  
execute metodu - RetryCallback + RecoveryCallback
Örnek
Şöyle yaparız
Foo foo = template.execute(new RetryCallback<Foo>() {
  public Foo doWithRetry(RetryContext context) {
    // business logic here
  },
  new RecoveryCallback<Foo>() {
    Foo recover(RetryContext context) throws Exception {
          // recover logic here
    }
});
registerListener metodu
RetryListenerSupport sınıfı yazısına taşıdım

setBackOffPolicy metodu
FixedBackOffPolicy kullanılabilir.

setPolicyMap metodu
Örnek
Şöyle yaparız.
@Bean(name="myRetryTemplate")
public RetryTemplate retryTemplate() {

  RetryTemplate retryTemplate = new RetryTemplate();
  SimpleRetryPolicy simpleRetryPolicyCheck = new SimpleRetryPolicy();
  simpleRetryPolicyForOkta.setMaxAttempts(3);

  Map<Class<? extends Throwable>, RetryPolicy> policyMap = new HashMap<>();
  policyMap.put(Exception1.class, simpleRetryPolicyCheck );
  policyMap.put(Exception2.class, simpleRetryPolicyCheck );

  ExceptionClassifierRetryPolicy retryPolicy = new ExceptionClassifierRetryPolicy();
  retryPolicy.setPolicyMap(policyMap);
  retryTemplate.setRetryPolicy(retryPolicy);
  return retryTemplate;
}
setRetryPolicy metodu
SimpleRetryPolicy kullanılabilir. Belirtilen sayı kadar tekrar dener
TimeoutRetryPolicy kullanılabilir;


Hiç yorum yok:

Yorum Gönder