아빠는 개발자

[java] Api retry 호출 본문

Java/API

[java] Api retry 호출

father6019 2025. 2. 23. 17:35
728x90
반응형

 

1. 기본 try-catch를 활용한 수동 리트라이

단순하게 for 루프를 사용하여 재시도할 수 있습니다.

 

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ApiClient {
    private static final int MAX_RETRIES = 3;
    private static final int RETRY_DELAY_MS = 2000; // 2초 대기

    public static String callApi(String apiUrl) throws InterruptedException {
        for (int attempt = 1; attempt <= MAX_RETRIES; attempt++) {
            try {
                System.out.println("API 호출 시도: " + attempt);
                HttpURLConnection connection = (HttpURLConnection) new URL(apiUrl).openConnection();
                connection.setRequestMethod("GET");
                int responseCode = connection.getResponseCode();
                if (responseCode == 200) {
                    return "API 호출 성공!";
                } else {
                    throw new IOException("응답 코드: " + responseCode);
                }
            } catch (IOException e) {
                System.err.println("API 호출 실패: " + e.getMessage());
                if (attempt == MAX_RETRIES) {
                    System.err.println("최대 재시도 횟수 도달. 실패 처리.");
                    throw new RuntimeException("API 호출 실패", e);
                }
                Thread.sleep(RETRY_DELAY_MS); // 재시도 전 대기
            }
        }
        return null;
    }

    public static void main(String[] args) throws InterruptedException {
        String apiUrl = "https://example.com/api";
        System.out.println(callApi(apiUrl));
    }
}

 

2. Spring Retry를 활용한 리트라이 처리

Spring 환경이라면 Spring Retry를 사용하여 보다 깔끔하게 구현할 수 있습니다.

📦 1) 의존성 추가 (pom.xml):

 

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

 

 

import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.HttpServerErrorException;

@EnableRetry
@Service
public class ApiService {

    private final RestTemplate restTemplate = new RestTemplate();

    @Retryable(
        value = { HttpServerErrorException.class },
        maxAttempts = 3,
        backoff = @Backoff(delay = 2000))
    public String callApi(String url) {
        return restTemplate.getForObject(url, String.class);
    }
}

 

 

3. resilience4j를 사용한 리트라이

보다 강력한 장애 처리 및 회복 기능이 필요하다면 resilience4j 라이브러리를 사용할 수 있습니다.

📦 1) 의존성 추가 (pom.xml):

 

import io.github.resilience4j.retry.annotation.Retry;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ApiService {

    private final RestTemplate restTemplate = new RestTemplate();

    @Retry(name = "apiRetry", fallbackMethod = "fallback")
    public String callApi(String url) {
        return restTemplate.getForObject(url, String.class);
    }

    public String fallback(String url, Exception e) {
        return "API 호출 실패 - 대체 응답 제공";
    }
}

 

 

💡 4. 리트라이 시 고려할 점

  • 📌 백오프 전략 (Backoff Strategy): 재시도 간 지수적 대기 시간을 두어 과도한 트래픽을 방지합니다.
  • 최대 재시도 횟수 설정: 무한 루프 방지를 위해 제한을 둡니다.
  • 🛡 회로 차단기(Circuit Breaker)와 연계: 지속적인 실패 시 호출을 중단하여 시스템 보호.
728x90
반응형

'Java > API' 카테고리의 다른 글

[java] API 성능개선  (1) 2023.11.26
[java] API method cache  (1) 2023.10.28
[java] API Controller에서 데이터를 받아오는 방법  (1) 2023.10.28
[java] API - geo distance  (0) 2023.10.21
[java] API - 검색 api 성능 개선 final  (0) 2023.10.14