Spring Boot/MSA
Spring Boot MSA OpenFeign
최-코드
2024. 7. 20. 14:10
OpenFeign은 프록시를 이용해 Eureka에서 활성화된 인스턴스를 조회한다음 해당 인스턴스의 메소드를 실행하게 된다. 이 때 spring cloud load balancer를 통해 로드 밸런싱을 수행하며 요청을 보내고 응답을 받는다.
//spring.application.name과 동일하게 설정해야 한다.
//eureka 서버를 참고해서 가져오는데, eureka 서버는 application.name을 통해 인스턴스의 이름을 설정한다.
@FeignClient(name = "currency-exchange")
public interface CurrencyExchangeProxy {
/*
currency-exchange controller의 있는 꼴 그대로 가져오기
응답이 json 형태이므로 CurrencyConversion에 매핑됨 (json 요청이 dto에 매핑되는 것과 같음)
*/
@GetMapping("/currency-exchange/from/{from}/to/{to}")
CurrencyConversion retrieveExchangeValue(
@PathVariable String from, @PathVariable String to);
}
OpenFeign을 사용하지 않을 때는 RestTemplate를 사용하여 요청을 보내고 응답을 보내야 한다.
@GetMapping("/currency-conversion/from/{from}/to/{to}/quantity/{quantity}")
public CurrencyConversion calculateCurrencyConversion(
@PathVariable String from, @PathVariable String to,
@PathVariable BigDecimal quantity) {
HashMap<String, String> uriVariables = new HashMap<>();
uriVariables.put("from", from);
uriVariables.put("to", to);
ResponseEntity<CurrencyConversion> responseEntity = new RestTemplate().getForEntity("http://localhost:8000/currency-exchange/from/{from}/to/{to}",
CurrencyConversion.class, uriVariables);
CurrencyConversion currencyConversion = responseEntity.getBody();
return new CurrencyConversion(currencyConversion.getId(), from, to, quantity, currencyConversion.getConversionMultiple(), quantity.multiply(currencyConversion.getConversionMultiple()), currencyConversion.getEnvironment());
}
OpenFeign을 이용하면 코드를 대폭 줄일 수 있다.
@RestController
@RequiredArgsConstructor
public class CurrencyConversionController {
private final CurrencyExchangeProxy currencyExchangeProxy;
@GetMapping("/currency-conversion-feign/from/{from}/to/{to}/quantity/{quantity}")
public CurrencyConversion calculateCurrencyConversionFeign(
@PathVariable String from, @PathVariable String to,
@PathVariable BigDecimal quantity) {
CurrencyConversion currencyConversion = currencyExchangeProxy.retrieveExchangeValue(from, to);
return new CurrencyConversion(currencyConversion.getId(), from, to, quantity, currencyConversion.getConversionMultiple(), quantity.multiply(currencyConversion.getConversionMultiple()), currencyConversion.getEnvironment());
}
}