Backend
home
🪓

ApiTemplate 분리 - 환율정보 API의 기본 틀

생성일
2025/01/24 05:52
태그
ApiTemplate
환율정보 API로부터 환율을 가져오는 기능을 제공하는 오브젝트
API 호출과 정보 추출의 기본 틀 제공
두 가지 콜백을 이용
유사한 여러 오브젝트에서 재사용 가능
ApiTemplate
package tobyspring.hellospring.api; import com.fasterxml.jackson.core.JsonProcessingException; import java.io.IOException; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; public class ApiTemplate { public static BigDecimal getExRate(String url, ApiExecutor apiExecutor, ExRateExtractor exRateExtractor) { URI uri; // URL -> URI 변경 try { uri = new URI(url); } catch (URISyntaxException e) { throw new RuntimeException(e); } String response; try { response = apiExecutor.execute(uri); } catch (IOException e) { throw new RuntimeException(e); } // build gradle에서 의존성 추가 // 'com.fasterxml.jackson.core:jackson-databind:2.12.5' try { return exRateExtractor.extract(response); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
Java
복사
HttpClientApiExecutor
package tobyspring.hellospring.api; import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class HttpClientApiExecutor implements ApiExecutor { @Override public String execute(URI uri) throws IOException { HttpRequest request = HttpRequest.newBuilder() .uri(uri) .GET() .build(); try { return HttpClient.newBuilder() .build() .send(request, HttpResponse.BodyHandlers.ofString()).body(); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
Java
복사
WebApiExRateProvider
package tobyspring.hellospring.exrate; import tobyspring.hellospring.api.*; import tobyspring.hellospring.payment.ExRateProvider; import java.math.BigDecimal; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class WebApiExRateProvider implements ExRateProvider { ApiTemplate apiTemplate = new ApiTemplate(); @Override public BigDecimal getExRate(String currency) { String url = "https://open.er-api.com/v6/latest/" + currency; return apiTemplate.getExRate(url, new HttpClientApiExecutor(), new ErApiExRateExtractor()); // 콜백 } }
Java
복사