MSA 공부 (Microservice간 통신 2) - 20

진병욱·2023년 11월 21일

Spring Cloud MSA 공부

목록 보기
20/20
post-thumbnail

먼저 글 작성에 앞서 해당 시리즈는 Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA) 강의를 참고하여 필요한 내용들을 정리한 것임을 밝힙니다.

FeignClient는 RestTemplate보다 좀 더 쉽게 사용이 가능하다는 장점이 있다.
하지만 해당 FeignClient를 사용하기 위해서는 해당 API에 대해서 잘 알고 있어야 한다는 단점도 존재한다.

FeignClient

  • REST Call을 추상화 한 Spring Cloud Netflix 라이브러리
  • 로드밸런스 지원

사용법

사전 준비

종속성

implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'

annotaion

  • @EnableFeignClients

인터페이스

@FeignClient(name="second-service")
public interface SecondServiceClient{

    @GetMapping("/port")
    String getPort();
}

코드

인터페이스

@FeignClient(name = "second-service")
public interface SecondServiceClient {

    @GetMapping("/port23")
    String getPort();

}

controller

@RequiredArgsConstructor
public class FirstServiceController{
	private final SecondServiceClient secondServiceClient;
    
    @GetMapping("/second-service/port")
    public String getSecondServicePort() {
    	String port = secondServiceClient.getPort();
        return port;
    }

}

예외 처리

로그 사용

Bean 생성

@Bean
public Logger.Level feignLoggerLevel() {
	return Logger.Level.FULL;
}

예외 처리

FeignException 처리

  • try, catch를 통한 에러 메시지 출력

  • 코드

    @RequiredArgsConstructor
    public class FirstServiceController{
        private final SecondServiceClient secondServiceClient;
    
        @GetMapping("/second-service/port")
        public String getSecondServicePort() {
            try {
                String port = secondServiceClient.getPort();
            } catch(FeignException e) {
                log.warn(e.getMessage());
            }
            return port;
        }
    
    }

ErrorDecoder 이용

  • try, catch를 이용하기 보다, error 상태에 따른 여러 상황처리를 하기 좀 더 유용
  • 코드
@Component
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        switch (response.status()) {
            case 400:
                // 요청이 잘 못 되었을 경우의 처리
                return new ResponseStatusException(HttpStatusCode.valueOf(response.status()), "Bad Request");
            case 404:
                if (methodKey.contains("getPort")) {
                    return new ResponseStatusException(HttpStatusCode.valueOf(response.status()), "port is not found");
                }
                break;
            default:
                return new Exception(response.reason());
        }
        return null;
    }
}
profile
새로운 기술을 접하는 것에 망설임이 없고, 부족한 것이 있다면 항상 배우고자 하는 열정을 가지고 있습니다!

0개의 댓글