MSA

[MSA] Spring Boot - Feign Client 란? Rest Api 호출

차노도리 2023. 4. 24. 00:33

Feign Client

  • Netfix에서 개발된 Http client binder이다.
  • 간편하게 Rest Api를 호출할 수 있다.

 

의존성 주입 (build.gradle)

dependencies {
	implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
    ...
}

 

Applicatoin - 어노테이션 등록

  • @EnableFeignClients 등록
import ...

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class GugbabVocaServerApplication {

    ...


}

 

Feign Client - 인터페이스 생성

  • @FeignClient 어노테이션 추가
    • name : eureka서버에 등록되어있는 이름
package com.gugbab.gugbabservices.client;

import ...

@FeignClient(name = "GUGBAB-API-GATEWAY")
public interface VocaServerClient {

    @GetMapping("/voca-server/star/all/{userId}")
    StarsResponse getStarsByUser(@PathVariable String userId, @RequestHeader HttpHeaders headers);

}

 

Feign Client 사용 예시

package com.gugbab.gugbabservices.service;

import ...

@Service
@Slf4j
public class UserServicesImpl implements UserService {

	...
    VocaServerClient vocaServerClient;

    @Autowired
    public UserServicesImpl(VocaServerClient vocaServerClient,  ...) {

        this.vocaServerClient = vocaServerClient;
        ...
    }
    
    @Override
    public UserDto getUserByUserId(String userId, HttpHeaders headers) {

		...

        // feign Client 사용
         StarsResponse stars = vocaServerClient.getStarsByUser(userId,headers);

        ...
        
    }
    
}