ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Feign Client 구현 - 1
    [공부] 프로그래밍/Spring・Spring Boot (JAVA) 2024. 5. 21. 11:29

     
    ♧ 전체 코드 : 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

     

    Feign Client

    HTTP API 호출을 인터페이스 기반으로 쉽게 할 수 있게 해주는 클라이언트입니다. Feign을 사용하면 REST API 호출을 위한 코드 작성을 대폭 줄일 수 있습니다. 인터페이스에 메서드와 HTTP 메서드, URL 매핑을 정의하면, Feign이 이를 구현하여 실제 HTTP 요청을 수행합니다.

    • Connection/Read Timeout : 외부 서버와의 통신 시, 설정이 가능
    • Interceptor : 외부로 요청이 나가지 전에 만약 공통적으로 처리를 해야 하는 부분이 있다면 Interceptor를 재정의 하여 처리 가능
    ※ Interceptor :
    소프트웨어 설계에서 요청(request)과 응답(response) 사이의 흐름을 가로채 특정 작업을 수행할 수 있게 해주는 구성 요소이다. 주로 웹 애플리케이션에서 사용되며, 클라이언트 요청을 처리하는 전, 중, 후에 다양한 로직을 추가할 수 있다. 인터셉터는 스프링 프레임워크에서 주로 사용되며, HandlerInterceptor인터페이스를 구현하여 커스터마이징 할 수 있다.
    • CustomLogger : request/response 등 운영을 위한 Log
    • ErrorDecoder : 요청에 대해 정상 응답이 아닌 경우, 핸들링이 가능

    Feign Client 구현

    ① build.gradle 수정
    : feign client를 사용할 수 있도록 디펜던시 추가하기

    ext {
    	/**
    	 * Spring Boot and springCloudVersion must be compatible.
    	 * 2.6.x, 2.7.x (Starting with 2021.0.3) = 2021.0.x
    	 * ref : https://spring.io/projects/spring-cloud
    	 */
    	// Feign
    	set('springCloudVersion', '2023.0.1')
    
    	set('commonsLangVersion', '3.12.0')
    }
    
    dependencyManagement {
        imports {
            mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
        }
    }
    
    // Feign
    implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'

    ② 메인 클래스에 이하를 추가

    @EnableFeignClients

    Spring Cloud Netflix Feign을 활성화하는 데 사용되는 애너테이션이다. Feign은 HTTP 기반의 외부 서비스와 통신하기 위한 REST 클라이언트를 간단하게 생성할 수 있도록 도와주는 라이브러리이다. 이 애너테이션을 사용하면, 지정된 패키지에서 Feign 클라이언트 인터페이스를 스캔하고, 해당 인터페이스에 대한 구현체를 생성한다.
    DemoFeignClient 작성
    : 외부 API를 호출하기 위한 Feign Client 인터페이스를 정의한다. @FeignClient 어노테이션을 사용하여 외부 서비스의 URL과 함께 클라이언트를 설정한다. (@FeignClient의 name과 url은 application.yaml에 기입)

    @FeignClient(
            name = "demo-client",
            url = "${feign.url.prefix}",
            configuration = DemoFeignConfig.class)
    public interface DemoFeignClient {
        @GetMapping("/get") // "${feign.url.prefix}/get"으로 요청
        ResponseEntity<BaseResponseInfo> callGet(@RequestHeader("customHeader") String customHeader,
                                                 @RequestParam("name") String name,
                                                 @RequestParam("age") Long age);
    
        @PostMapping("/post") // "${feign.url.prefix}/post"로 요청
        ResponseEntity<BaseResponseInfo> callPost(@RequestHeader("customHeader") String customHeader,
                                                  @RequestBody BaseRequestInfo baseRequestInfo);
    
        @GetMapping("/errorDecoder") // "${feign.url.prefix}/errorDecoder"로 요청
        ResponseEntity<BaseResponseInfo> callErrorDecoder();
    }

     
    ④ DemoService 작성
    : DemoFeignClient를 사용하는 서비스 클래스를 작성한다. 정의한 Feign Client를 서비스 클래스에서 주입받아 사용하며 이 서비스 클래스는 외부 API를 호출하는 메서드를 제공한다.

    @Service
    @RequiredArgsConstructor
    public class DemoService {
        private final DemoFeignClient demoFeignClient;
    
        public String get() {
            ResponseEntity<BaseResponseInfo> response = demoFeignClient.callGet("CustomHeader",
                    "CustomName",
                    1L);
            System.out.println("Name : " + response.getBody().getName());
            System.out.println("Age : " + response.getBody().getAge());
            System.out.println("Header : " + response.getBody().getHeader());
            return "get";
        }
    
        public String post() {
            BaseRequestInfo requestBody = BaseRequestInfo.builder()
                    .name("customName")
                    .age(1L)
                    .build();
            ResponseEntity<BaseResponseInfo> response = demoFeignClient.callPost("CustomHeader",
                    requestBody);
            System.out.println("Name : " + response.getBody().getName());
            System.out.println("Age : " + response.getBody().getAge());
            System.out.println("Header : " + response.getBody().getHeader());
            return "post";
        }
    
        public String errorDecoder() {
            demoFeignClient.callErrorDecoder();
            return "errorDecoder";
        }
    }

    DemoController 작성
    : DemoService를 컨트롤러에서 사용하여 API를 호출하는 엔드포인트를 제공한다.
     

    출처 : 패스트캠퍼스 10개 프로젝트로 완성하는 백엔드 웹개발(Java/Spring) 초격차 패키지 Online

    '[공부] 프로그래밍 > Spring・Spring Boot (JAVA)' 카테고리의 다른 글

    Feign Client 구현 - 3  (0) 2024.05.22
    Feign Client 구현 - 2  (0) 2024.05.21
    비동기 프로그래밍 구현  (0) 2024.05.20
    Spring Multi Module 구현  (0) 2024.05.16
    Spring Batch 구현 - 7  (0) 2024.05.14
Designed by Tistory.