[Spring Boot] Feign Client 사용법

 


내 서비스에서 다른 API를 호출해서 결과를 받을 수 있는 방법을 알아보자.

유사한 API로는 RestTemplate이 있지만 Spring Cloud에서 제공하는 Feign client를 이용해 다른 서버 API 호출 방법을 설명해 보겠다.

호출 할 URL은 https://randomuser.me/api/?nat=us 인데 매번 호출 할 때마다 결과 값은 다르다.

결과 값 중 성별/이메일만 응답 줄 수 있도록 예제를 작성했다.


[환경]

Windows 10
IntelliJ 
java 11
gradle-7.6

[Gradle 설정]

//feign
implementation platform("org.springframework.cloud:spring-cloud-dependencies:2021.0.5")
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'

 


[프로그램 전체]

MainApplication class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableFeignClients  //<================ 메인에서 추가 해줘야 한다.
@EnableScheduling
@SpringBootApplication
public class MainApplication {
        public static void main(String[] args) {
            SpringApplication.run(MainApplication.class, args);
         }
}
UserClient class
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(name = "userClient", url = "https://randomuser.me") //<=====호출할 URL 설정
public interface UserClient {

    @GetMapping(value = "/api/") //<========== 함수 호출시  https://randomuser.me/api/ 가 되도록 설정
    GetUsersResponse getUsers(@RequestParam("nat") String nation); 
}
GetUsersResponse class
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.List;

@Getter
@AllArgsConstructor
@NoArgsConstructor
public class GetUsersResponse {
    private List<Result> results;

    @Getter
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Result {
        private String gender;
        private String email;
    }
}
TestController - swagger 설정이 되어 있어야 합니다.
@Slf4j
@RequestMapping("/v1")
@RestController
@AllArgsConstructor
@Api(tags = {"01. 테스트 API"})
public class TestController {

    private final UserClient userClient;

    @GetMapping("/feign")
    @ApiOperation(value = "Feign 테스트")
    public CommonResponse<?> feign() {
        GetUsersResponse users = userClient.getUsers("nat=us"); //<=== API에 파라미터로 nat=us를 넣는다.
        return CommonResponse.createSuccessWithNoContent();
    }

}

 

[실행 결과]

{
  "results": [
    {
      "gender": "female",
      "email": "leonie.gonzalez@example.com"
    }
  ]
}

 

 

 

반응형

+ Recent posts