ํ๋ก์ ํธ๋ฅผ ์งํํ๋ ์ค ์ฐ์ฐํ HTTP ์์ฒญ์ ๋ณด๋ด์ผ ํ ์ผ์ด ์๊ฒผ๋ค. HTTP ํด๋ผ์ด์ธํธ๋ก๋ ์ผ๋ฐ์ ์ผ๋ก RestTemplate์ด๋ WebClient๋ฅผ ๋ง์ด ์ฌ์ฉํ์ง๋ง, ๋ทํ๋ฆญ์ค์์ ๊ฐ๋ฐํ FeignClient์ ํฅ๋ฏธ๊ฐ ์๊ฒจ ์ง์ ์ ์ฉํด๋ณด์๋ค.
๋ทํ๋ฆญ์ค์์ ๊ฐ๋ฐํ HTTP Client๋ก, ์๋๋ Spring Cloud Netflix Feign์ ์ผ๋ถ์์ง๋ง, ์ดํ ๋ทํ๋ฆญ์ค๊ฐ ์ ์ง๋ณด์์์ ์์ ๋ผ๋ฉด์ ํ์ฌ๋ OpenFeign์ด๋ผ๋ ์ด๋ฆ์ผ๋ก ์ปค๋ฎค๋ํฐ ์ฃผ๋์ ์คํ ์์ค ํ๋ก์ ํธ๋ก ์ ํ๋์๋ค. Spring Cloud๋ ์ฌ์ ํ ์ด๋ฅผ ํตํฉํด ์ฌ์ฉํ๊ณ ์์ผ๋ฉฐ, ์ ์ธํ ๋ฐฉ์์ผ๋ก HTTP ์์ฒญ์ ์์ฑํ ์ ์์ด ์ฝ๋์ ๊ฐ๊ฒฐ์ฑ๊ณผ ๊ฐ๋ ์ฑ์ ๋์ด๋ ๋ฐ ์ ์ฉํ๋ค.
MSA์ ์๋น์ค๋ค์ด ๋ง์์ง๋ฉด์ ๊ฐ๊ฐ์ ์๋น์ค๋ค ์ฌ์ด์ ํต์ ์ด ๋ง์์ง๊ฒ ๋์๋๋ฐ, ์ด๋ FeignClient๋ฅผ ์ ์ฉํ๋ฉด ๊ธฐ์กด ๋ฐฉ์๋ค๋ณด๋ค ์กฐ๊ธ ๋ ํธ๋ฆฌํ๊ฒ ์ฌ์ฉ ํ ์ ์๋ค. ๊ทธ๋ฆฌ๊ณ ์ฝ๋์ ์ค๋ณต๋ ์ค์ผ ์ ์๋ค.
dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:2025.0.0"
}
}
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
์คํ๋ง๋ถํธ์์ ํธํ์ฑ ์ฃผ์!!
@SpringBootApplication
@EnableFeignClients(basePackages = "com.deal4u.fourplease.domain.payment")
public class FourPleaseBeApplication {
public static void main(String[] args) {
SpringApplication.run(FourPleaseBeApplication.class, args);
}
}
@EnableFeignClients ์ด๋
ธํ
์ด์
์ ๋ถ์ฌ์ฃผ๋ฉด ๋๋๋ฐ ํ์์ ๋ฐ๋ผ ๋ฒ์๋ฅผ ์ง์ ๊ฐ๋ฅํ๋ค.
@FeignClient(
name = "tossClient",
url = "https://api.tosspayments.com",
configuration = TossFeignConfig.class
)
public interface TossApiClient {
@PostMapping("/v1/payments/confirm")
TossPaymentConfirmResponse confirmPayment(
@RequestBody
TossPaymentConfirmRequest request
);
}
@Configuration
public class TossFeignConfig {
@Value("${toss.secret-key}")
private String secretKey;
@Bean
public RequestInterceptor requestInterceptor() {
return requestTemplate -> {
String encodedKey = Base64.getEncoder().encodeToString((secretKey + ":").getBytes());
requestTemplate.header("Authorization", "Basic " + encodedKey);
requestTemplate.header("Content-Type", "application/json");
};
}
}
๋ด ํ๋ก์ ํธ์์๋ ์ธ๋ถ ๊ฒฐ์ API์ธ ํ ์คํ์ด๋จผ์ธ API๋ฅผ ํธ์ถํด์ผ ํ๋ ๋ก์ง์ด ํ์ํ๋ค. ๋ฐ๋ผ์ HTTP ์์ฒญ์ ๋ณด๋ค ์ ์ธ์ ์ด๊ณ ๊ฐ๊ฒฐํ๊ฒ ์์ฑํ ์ ์๋ FeignClient๋ฅผ ํ์ฉํด ๊ตฌํํ๋ค. ์ ์์๋ /v1/payments/confirm ์๋ํฌ์ธํธ๋ก ๊ฒฐ์ ์น์ธ ์์ฒญ์ ๋ณด๋ด๋ ์ธํฐํ์ด์ค์ด๋ฉฐ, TossFeignConfig๋ฅผ ํตํด ์ธ์ฆ ํค๋์ Content-Type ๋ฑ์ ์ ์ญ ์ค์ ์ผ๋ก ์ง์ ํ๋ค. ์ด์ฒ๋ผ ์ธ๋ถ API ์ฐ๋ ์ ํ์ํ ๊ณตํต ํค๋๋ฅผ RequestInterceptor์์ ์ฒ๋ฆฌํจ์ผ๋ก์จ ์ฝ๋์ ์ฌ์ฌ์ฉ์ฑ๊ณผ ์ ์ง๋ณด์์ฑ์ ๋์ผ ์ ์์๋ค.