728x90
반응형
스프링 부트 애플리케이션을 개발하다 보면
네트워크 장애, 데이터베이스 충돌, API 호출 실패 등으로 인해
자동 재시도(Retry) 메커니즘이 필요할 때가 많습니다.
Spring Retry를 사용하면 일정 횟수 재시도, 지연 시간(Backoff) 적용, 특정 예외에 대해서만 재시도 등을 쉽게 구현할 수 있습니다.
✅ 1. Spring Retry란?
✔️ Spring Retry 주요 기능
@Retryable
애너테이션으로 간편하게 자동 재시도@Recover
를 활용한 최종 예외 처리- 백오프(Backoff) 전략을 적용하여 서버 부담 최소화
- 트랜잭션, 네트워크 오류, API 장애 등 다양한 상황에서 재시도 가능
✅ 2. Spring Retry 설정
🔹 2.1 Spring Boot 프로젝트에 Spring Retry 추가
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.3.4</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
✅ 3. 실무 적용 예제 – 트랜잭션 내 재시도
🔹 3.1 트랜잭션 내에서 재시도 적용하기
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.annotation.Recover;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class TransactionRetryService {
private int attempt = 1;
@Transactional
@Retryable(
value = {DeadlockLoserDataAccessException.class},
maxAttempts = 5,
backoff = @Backoff(delay = 1000, multiplier = 2)
)
public void updateDatabase() {
System.out.println("트랜잭션 재시도 횟수: " + attempt);
attempt++;
if (Math.random() < 0.7) {
throw new DeadlockLoserDataAccessException("Deadlock 발생!", null);
}
System.out.println("✅ 트랜잭션 성공적으로 완료!");
}
@Recover
public void recoverTransactionFailure(DeadlockLoserDataAccessException e) {
System.err.println("❌ 트랜잭션 재시도 실패. 예외 메시지: " + e.getMessage());
}
}
✅ 4. 실무 적용 예제 – API 호출 재시도
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.annotation.Recover;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.ResourceAccessException;
@Service
public class ApiRetryService {
private final RestTemplate restTemplate = new RestTemplate();
@Retryable(
value = ResourceAccessException.class,
maxAttempts = 3,
backoff = @Backoff(delay = 2000)
)
public String callExternalApi() {
System.out.println("🔄 API 호출 재시도 중...");
return restTemplate.getForObject("https://api.example.com/data", String.class);
}
@Recover
public String recoverApiFailure(ResourceAccessException e) {
System.err.println("❌ API 호출 실패! 대체 응답 제공");
return "대체 응답 데이터";
}
}
✅ 5. Spring Retry vs Resilience4j 비교
기능 | Spring Retry | Resilience4j |
---|---|---|
재시도 기능 | ✅ 지원 | ✅ 지원 |
백오프 전략 | ✅ 지원 | ✅ 지원 |
Circuit Breaker | ❌ 미지원 | ✅ 지원 |
캐시 기능 | ❌ 미지원 | ✅ 지원 |
✔️ Resilience4j는 서킷 브레이커 기능을 제공하여 대규모 장애 대응에 유리합니다.
✅ 6. 결론
Spring Retry를 사용하면 트랜잭션 내 충돌 해결, API 장애 대응, 네트워크 재시도 등
다양한 상황에서 안정적인 서비스를 구축할 수 있습니다.
728x90
반응형
'Spring & Spring Boot 실무 가이드' 카테고리의 다른 글
[Spring] Spring Boot에서 API 응답 속도를 높이는 5가지 방법 (2) | 2025.01.21 |
---|---|
[Spring] Spring Batch로 사용자 활동 로그를 집계하여 실시간 보고서 자동화하기 (0) | 2025.01.20 |
[Spring]Spring 개발자를 위한 Annotation 원리와 커스텀 Annotation 실습 (0) | 2025.01.18 |
[spring] AOP(관점 지향 프로그래밍) 이해하기: 실용적인 예제로 배우는 AOP (1) | 2024.01.21 |
[Spring] yml 암호화를 해보자(feat. jasypt) (2) | 2024.01.03 |