Develop
Spring Retry
kimyuuum
2021. 2. 2. 10:00
Spring Retry
실패한 동작을 자동으로 다시 호출하는 기능 제공. 네트워크 결함과 같이 오류가 일시적으로 발생할 경우 유용함.
Enabling
@Configuration 클래스에 @EnableRetry 애너테이션을 추가해야함.
Retry
@Retryable 을 사용하여 실패 시 재시도할 메서드 호출을 작성 가능하다.
@Service
public class RetryService{
static int retryCount = 0;
@Retryable(value = {SQLException.class},
maxAttempts = 2,
backoff = @Backoff(delay = 2000))
int countContents() throws SQLException {
retryCount++;
System.out.println("retryCount" + retryCount);
if (retryCount ==2){
return 100;
} else {
throw new SQLException;
}
}
}
메서드에서 SQLException을 발생시키는 경우에 재시도한다. 최대 2번의 재시도를 2000ms의 텀을 두고 시도함. 여기서는 2번째 시도를 진행할 경우 그냥 성공했다 가정하고 100을 return함.
@Retryable을 아무 속성 없이 사용할 경우, 예외가 발생하여 메서드가 실패하면 기본적으로 1초의 지연으로 최대 3번 재시도한다.
@Recover
Recover 어노테이션은 @Retryable 메서드가 지정된 예외로 실패할 때 별도의 복구 메서드를 정의하는 데 사용됨.
@Retryable(
value = {SQLIntegrityConstraintViolationException.class},
maxAttempts = 4,
backoff = @Backoff(delay = 2000))
int deleteContents(String sql) throws SQLIntegrityConstraintViolationException {
retryCount3++;
System.out.println("retryCount " + retryCount3);
throw new SQLIntegrityConstraintViolationException();
}
@Recover
public int recover(SQLIntegrityConstraintViolationException e, String sql){
System.out.println("Recover called : message = " + e.getMessage() + ", sql = " + sql );
return 50;
}
deleteContents
에서 SQLIntegrityConstraintViolationException이 발생하면, maxAttempt만큼 재시도 후 그래도 복구가 안되었을 경우에는, recover() 메서드가 최종으로 호출된다.
recover 선언 시 주의할 점
처리하려는 메서드의 매개변수와, 리턴 타입을 동일하게 선언해야함.