22. Feign Client

Feign Client

  • REST Call을 추상화 한 Spring Cloud Netflix 라이브러리 이다.

사용방법

  • 호출하려는 HTTP Endpoint에 대한 Interface를 생성
  • @FeignClient 선언
  • Load Balanced 지원

참조

- https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/

 

Spring Cloud OpenFeign

Feign is a declarative web service client. It makes writing web service clients easier. To use Feign create an interface and annotate it. It has pluggable annotation support including Feign annotations and JAX-RS annotations. Feign also supports pluggable

docs.spring.io

 

| User-service에 Feign Client 설정

의존성 추가

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version></version>
        </dependency>

UserServiceApplication.java

  • @EnableFeignClients을 추가
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class UserServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

OrderServiceClient.java

package com.kyhslam.userservice.client;

import com.kyhslam.userservice.vo.ResponseOrder;
import org.springframework.cloud.openfeign.FeignClient;

@FeignClient(name = "order-service")
public interface OrderServiceClient {

    @GetMapping("/order-service/{userId}/orders")
    List<ResponseOrder> getOrders(@PathVariable String userId);

}

UserServiceImpl.java

public UserDto getUserByUserId(String userId) {
        UserEntity userEntity = userRepository.findByUserId(userId);

        if (userEntity == null) {
            throw new UsernameNotFoundException("User not found");
        }

        UserDto userDto = new ModelMapper().map(userEntity, UserDto.class);

        //List<ResponseOrder> orders = new ArrayList<>();

        /* Using as Rest Template */
       /* String orderUrl = String.format(env.getProperty("order_service.url"), userId); //"http://localhost:8000/order-service/%s/orders";
        ResponseEntity<List<ResponseOrder>> orderListResponse =
                    restTemplate.exchange(orderUrl, HttpMethod.GET, null,
                        new ParameterizedTypeReference<List<ResponseOrder>>() {

                });
        List<ResponseOrder> orderList = orderListResponse.getBody();*/

        /* Using a Feign Client */
        List<ResponseOrder> orderList = orderServiceClient.gtOrders(userId);

        userDto.setOrders(orderList);

        return userDto;
    }

 

댓글

Designed by JB FACTORY