외부 Open API를 이용해서 데이터를 가져올 때 RestTemplate를 사용했으나 deprecated 됐다.
그렇다고 WebClient를 사용하기에는 Webflux 의존성을 주입해야 한다.
너무 부담스러운 느낌..
Spring 6.1 버전부터 RestClient라는 기능을 제공해 준다.
RestTemplate + WebClient 짬뽕시킨 느낌이다.
Spring Boot 3.2 M1 버전부터 사용 가능하다고 한다.
https://spring.io/blog/2023/07/13/new-in-spring-6-1-restclient
해당 기능을 이용해서 업비트 원화 마켓에 상장된 코인들을 가져와봤다.
@RequiredArgsConstructor
@Component
public class CoinScheduler {
private static final String UPBIT_MARKET_API_URL = "https://api.upbit.com/v1/market/all";
private static final Logger log = LoggerFactory.getLogger(CoinScheduler.class);
private final RestClient restClient = RestClient.create();
private final CoinRepository coinRepository;
// 한시간 마다 실행
@Scheduled(fixedRate = 1000 * 60 * 60)
public void fetchUpbitListingCoins() {
GetUpbitCoinRequestDto[] requestDtos = fetchUpbitCoinRequestDtos();
int fetchCount = 0;
for (GetUpbitCoinRequestDto requestDto : requestDtos) {
if (requestDto.market().startsWith("KRW-") && !coinRepository.existsByMarket(requestDto.market())) {
coinRepository.save(requestDto.fetch());
fetchCount++;
}
}
log.info("Fetching upbit listing coins: {}", fetchCount);
}
private GetUpbitCoinRequestDto[] fetchUpbitCoinRequestDtos() {
return restClient.get()
.uri(UPBIT_MARKET_API_URL)
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, ((request, response) -> {
throw new CustomException(ErrorCode.INVALID_FETCHES_UPBIT_COINS);
}))
.body(GetUpbitCoinRequestDto[].class);
}
}
public record GetUpbitCoinRequestDto(
String market,
String korean_name,
String english_name
) {
public CoinEntity fetch() {
return CoinEntity.builder()
.market(this.market)
.koreanName(this.korean_name)
.englishName(this.english_name)
.build();
}
}