Project/Buy me If you can

Buyme TIL240827 MSA 환경에서 api gateway 를 통한 데이터 통신

Albosa2lol 2024. 8. 29. 21:46
  • 멀티 모듈 화 후 API 게이트를 통해 각 모듈을 연결할 때, 전환된 환경에서 다른 모듈에 있는 엔티티를 직접 참조할 수 없는경우, 어떤 방법을 사용하는게 좋은지?

방법은 크게 3가지가 있다.

  • REST API 를 통한 정보조회
  • RestTemplate
  • WebClient

현재 MSA 환경에서 API 게이트웨이를 통해 다른 독립적인 (세분화된) 서비스들과 통신을 하는 것이기 때문에, REST API (http response)를 통해서 하는 것이 맞다.

 

MSA 환경에서 order-service 를 쓰는데, Product 정보가 필요한 경우를 예상해보자

 

 

1. WebClient.Builder 사용을 위한 의존성 추가

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
}

 

2. Order-service 내에 Product DTO 생성

package com.example.buyme.order.dto;

import lombok.Data;

@Data
public class Product {
    private Long productId;
    private String productName;
    private String productDescription;
    private int productPrice;
    private int productStock;
}

 

OrderService 내에 Product 정보를 API를 통해 가져오는 메소드

@Service
@RequiredArgsConstructor
public class OrderService {

    private final OrderRepository orderRepository;
    private final OrderItemRepository orderItemRepository;
    private final WebClient.Builder webClientBuilder;

    
    private Product getProductById(Long productId) {
        return webClientBuilder.build()
                .get()
                .uri("http://gateway-service/products/" + productId)
                .retrieve()
                .bodyToMono(Product.class)
                .block();
    }

    // 기타 메소드들...
}

 

Product 클래스를 order-service 내에서 정의된 DTO로 사용하여, product-service와의 통신을 할 수 있다.