-
Feign Client 구현 - 2[공부] 프로그래밍/Spring・Spring Boot (JAVA) 2024. 5. 21. 14:52
♧ 전체 코드 : https://github.com/woodisco/feign-client
GitHub - woodisco/feign-client: feign-client 공부
feign-client 공부. Contribute to woodisco/feign-client development by creating an account on GitHub.
github.com
Interceptor 구현
외부로 요청이 나가지 전에 만약 공통적으로 처리를 해야하는 부분이 있다면 Interceptor를 재정의 하여 처리 가능하다.
① DemoFeignInterceptor 작성
@RequiredArgsConstructor(staticName = "of") public class DemoFeignInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate template) { // get 요청일 경우 if(template.method() == Request.HttpMethod.GET.name()) { System.out.println("[GET] [DemoFeignInterceptor] queries : " + template.queries()); return; } // post 요청일 경우 String encodedRequestBody = StringUtils.toEncodedString(template.body(), UTF_8); System.out.println("[POST] [DemoFeignInterceptor] requestBody : " + encodedRequestBody); //새로운 requestBody 값으로 설정 template.body(encodedRequestBody); } }
▷ (staticName = "of") :
staticName 속성은 이 생성자를 호출하는 정적 팩토리 메서드의 이름을 지정하는 데 사용된다. 예를 들어 staticName = "of"
로 설정하면, 해당 생성자를 호출하는 정적 메서드 of 가 생성된다. 이를 통해 객체 생성 시 가독성이 향상될 수 있다.
▷ RequestInterceptor :
Spring Cloud OpenFeign에서 HTTP 요청을 인터셉트하고 수정하는 데 사용되는 인터페이스이다. 이를 사용하면 Feign 클라이언트가 서버로 전송하기 전에 HTTP 요청에 헤더를 추가하거나 다른 방식으로 요청을 변경할 수 있다.
▷ RequestTemplate :
Feign 클라이언트가 생성하는 HTTP 요청에 대한 템플릿을 나타내는 클래스이다. 이 클래스는 Feign의 HTTP 클라이언트에 의해 사용되어 요청의 특정 측면을 구성한다.
・ 헤더 추가 및 제거: header() 메서드를 사용하여 요청에 헤더를 추가하거나 제거
・ 쿼리 매개변수 추가: query() 메서드를 사용하여 쿼리 매개변수를 추가
・ 요청 URI 설정: uri() 메서드를 사용하여 요청의 URI를 설정
・ HTTP 메서드 설정: method() 메서드를 사용하여 요청의 HTTP 메서드를 설정
・ 요청 본문 설정: body() 메서드를 사용하여 요청 본문을 설정② DemoFeignConfig 수정
: DemoFeignInterceptor를 Bean으로 등록하기
@Configuration public class DemoFeignConfig { @Bean public DemoFeignInterceptor feignInterceptor() { return DemoFeignInterceptor.of(); // (staticName = "of") } }
출처 : 패스트캠퍼스 10개 프로젝트로 완성하는 백엔드 웹개발(Java/Spring) 초격차 패키지 Online
'[공부] 프로그래밍 > Spring・Spring Boot (JAVA)' 카테고리의 다른 글
Feign Client 구현 - 4 (0) 2024.05.22 Feign Client 구현 - 3 (0) 2024.05.22 Feign Client 구현 - 1 (0) 2024.05.21 비동기 프로그래밍 구현 (0) 2024.05.20 Spring Multi Module 구현 (0) 2024.05.16