Currency Conversion MicroService

shlee ⚡️·2023년 11월 15일
0

포트 구성

목표

  • 먼저 Currency Conversion Microservice를 만들고
  • Currency Exchange Microservice를 통신해 h2database에 있는 환율 데이터를 가져 올것임

01. Currency Conversion (Micro)Service 생성

의존성 목록

  • Dev tools
  • Actuator
  • Spring Web
  • Config Client

Currency Conversion Service(환전서비스) URL 및 응답 구조

url

http://localhost:8100/currency-conversion/from/USD/to/INR/quantity/10

Response Structure

{
  "id": 10001,
  "from": "USD",
  "to": "INR",
  "conversionMultiple": 65.00,
  "quantity": 10,
  "totalCalculatedAmount": 650.00,
  "environment": "8000 instance-id"
}

application.properties ( Currency-Conversion-Service )

spring.application.name=currency-conversion
spring.config.import=optional:configserver:http://localhost:8888
server.port=8100

CurrencyConversion

public class CurrencyExchange {
	private Long id;
	private String from;
	private String to;
	private BigDecimal quantity;
	private BigDecimal conversionMultiple;
	private BigDecimal totalCalculateAmount;
	private String environment;
	
	public CurrencyConversion() {
		super();
	}
	
	public CurrencyConversion(Long id, String from, String to, BigDecimal quantity, BigDecimal conversionMultiple,
			BigDecimal totalCalculateAmount, String environment) {
		this.id = id;
		this.from = from;
		this.to = to;
		this.conversionMultiple = conversionMultiple;
		this.quantity = quantity;
		this.totalCalculateAmount = totalCalculateAmount;
		this.environment = environment;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getTo() {
		return to;
	}

	public void setTo(String to) {
		this.to = to;
	}

	public BigDecimal getQuantity() {
		return quantity;
	}

	public void setQuantity(BigDecimal quantity) {
		this.quantity = quantity;
	}

	public BigDecimal getConversionMultiple() {
		return conversionMultiple;
	}

	public void setConversionMultiple(BigDecimal conversionMultiple) {
		this.conversionMultiple = conversionMultiple;
	}

	public BigDecimal getTotalCalculateAmount() {
		return totalCalculateAmount;
	}

	public void setTotalCalculateAmount(BigDecimal totalCalculateAmount) {
		this.totalCalculateAmount = totalCalculateAmount;
	}

	public String getEnvironment() {
		return environment;
	}

	public void setEnvironment(String environment) {
		this.environment = environment;
	}

CurrencyExchangeController (하드코딩)

@RestController
public class CurrencyConversionController {
	@GetMapping("/currency-conversion/{from}/USD/{to}/INR/quantity/{quantity}")
	public CurrencyConversion calculateCurrencyConversion(@PathVariable String from,
															@PathVariable String to,
															@PathVariable BigDecimal quantity) {
		
		return new CurrencyConversion(10001L, from, to, quantity, BigDecimal.ONE, BigDecimal.ONE, "" );
	}
}

브라우저 테스트

02. Conversion서비스 -> Exchange서비스 호출

CurrencyExchangeController - 수정

  • RestTemplate().getForEntity() ~~
@RestController
public class CurrencyConversionController {
	@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());
	}
}


그래서 결론은 우리가 Conversion에 어떤 국가의 돈은 어떤 국가의 돈으로 환전하고 수량은 얼마나하겠다 요청을 보내면
근데 환율은 Exchange가 가지고있으니 Conversion가 다시 Exchange에게 얘한테 요청해서 받아온다음
결과를 다시 Conversion로 계산 및 정리해서 리턴

03. Feign REST Client ★

위에처럼 마이크로서비스간 통신을 하려면 길고 지루한 코드들을 계속 작성해야 한다
그래서 스프링 프레임워크는 Feign Framework를 제공한다

pom.xml

  • openfeign 의존성 추가
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>

CurrencyExchangeProxy interface - 생성

  • @FeignClient(name = "currency-exchange", url = "localhost:8000")
  • GetMapping retrieveExchangeValue 메서드 추가
// 사용하(찾)고 싶은 spring.application.name=currency-exchange
@FeignClient(name = "currency-exchange", url = "localhost:8000")
public interface CurrencyExchangeProxy {
	
	@GetMapping("/currency-exchange/from/{from}/to/{to}")
	public CurrencyConversion retrieveExchangeValue(@PathVariable String from, @PathVariable String to);
}

CurrencyConversionServiceApplication - 수정

  • @EnableFeignClients 어노테이션 추가
@SpringBootApplication
@EnableFeignClients
public class CurrencyConversionServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(CurrencyConversionServiceApplication.class, args);
	}

}

CurrencyConversionController - 추가

  • @Autowired
    private CurrencyExchangeProxy proxy; // 추가
  • currency-conversion-feign // 추가
@RestController
public class CurrencyConversionController {
	
	@Autowired // 추가
	private CurrencyExchangeProxy proxy;
	
    // 추가
	@GetMapping("/currency-conversion-feign/from/{from}/to/{to}/quantity/{quantity}")
	public CurrencyConversion calculateCurrencyConversionFeign(@PathVariable String from
														, @PathVariable String to
														, @PathVariable BigDecimal quantity) {
		
        // 변경 된 점
		CurrencyConversion currencyConversion = proxy.retrieveExchangeValue(from, to);
		
		return new CurrencyConversion(currencyConversion.getId()
									, from, to, quantity
									, currencyConversion.getConversionMultiple()
									, quantity.multiply(currencyConversion.getConversionMultiple())
									, currencyConversion.getEnvironment());
	}
}

문제점

  • CurrencyExchangeProxy interface 에서
@FeignClient(name = "currency-exchange", url = "localhost:8000")
public interface CurrencyExchangeProxy {
	...
}

url이 하드코딩 되어있다 "localhost:8000"
8001, 8002... 포트가 늘어나면 동적으로 할당해 줘야 하는데..
이걸 위해 유레카 네이밍 서버가 필요하다

profile
흔들리지 말고.. 묵묵히

0개의 댓글