Spring Retry
메서드가 실패 하였을때 재 실행 할 수 있도록 도와주는 Spring AOP의 일종 이다.
네트워크 호출과 같은 일시적 문제가 있을 경우 사용한다.
build.gradle Dependency 추가
implementation group: 'org.springframework.retry', name: 'spring-retry', version: '1.3.1'
Retry 사용이 가능하도록 annotation 설정
@EnableRetry
@SpringBootApplication
public class RanchatApplication {
public static void main(String[] args) {
SpringApplication.run(RanchatApplication.class, args);
}
}
Retry 사용
@Service
public class RetryTestService {
private int cnt;
@Retryable(value = NullPointerException.class,
maxAttempts = 3,
backoff = @Backoff(delay = 2000),
recover = "recover2"
)
public void retryTest() {
System.out.println("retryCnt : " + cnt);
if (cnt++ < 5) {
throw new NullPointerException();
}
}
@Recover
public void recover11(Exception exception) {
System.out.println("recover@@@");
}
@Recover
public void recover2(Exception exception) {
System.out.println("recover222222");
}
}
- @Retryable 을 통해 재실행 가능한 메소드로 설정한다.
- value: 어떤 Exception 이 발생시 재실행을 시도하는지 설정, 없을시 모든 Exception에 대해 재실행
- maxAttempts: 최대 실행 횟수
- backoff: 재실행시 딜레이 시간 설정
- recover: 최대실행 횟수까지 실패 했을 경우 지정된 recover 메소드가 실행된다.
- recover메소드는 반드시 @Recover어노테이션과 첫번째 파라미터로 Retryable메소드에서 발생한 Exception을 받을 파라미터가 필요하다.
'SPRING' 카테고리의 다른 글
Spring Envers 로 자동 이력 관리 (0) | 2021.06.20 |
---|---|
Spring Event (0) | 2021.05.27 |
Spring Rest Docs 사용법 (0) | 2021.05.02 |
Spring Batch (0) | 2021.04.28 |
Spring RestTemplate (0) | 2021.04.20 |