PSD( Private-Self-Development )

Feign Client 본문

Backend/MSA

Feign Client

chjysm 2024. 4. 19. 10:48

Feign Client 란?

MSA 서버에서 다른 서버로 REST 통신을 하기 위한 추상화 된 인터페이스 

기존 Rest Template 방식 보다 직관적 이고 간단하다.

단, 기존 Rest Template 방식 보다 양 MSA 서버간의 구조를 확실히 알아야 하는 단점도 있다.

 

사용

1. 디펜던시 추가 

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

 

2.  어노테이션 추가

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}

 

3. 클라이언트 구현

@FeignClient(name = "order-service")
public interface OrderServiceClient {
    @GetMapping("order-service/{userId}/orders")
    List<ResponseOrder> getOrders(@PathVariable String userId);
}

 

4. 에러 디코더 구현

@Component
@RequiredArgsConstructor
public class FeignErrorDecoder implements ErrorDecoder {
    private final Environment env;
    @Override
    public Exception decode(String methodKey, Response response) {
        switch (response.status()){
            case 400:
                break;
            case 404:
                if(methodKey.contains("getOrders")){
                    return new ResponseStatusException(HttpStatus.valueOf(response.status()),
                            env.getProperty("order_service.exception.order_is_empty"));
                }
                break;
            default:
                return new Exception(response.reason());
        }
        return null;
    }
}

 

'Backend > MSA' 카테고리의 다른 글

MSA 장애 처리 및 분산 추적  (0) 2024.04.23
Kafka( 카프카 )  (0) 2024.04.22
Spring Cloud Config  (0) 2024.04.16
API Gateway  (0) 2024.03.26
Service Discovery  (1) 2024.01.09