Spring Cloud - 28. Micro Service간 통신 Feign client

목차

User service

// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@Slf4j
public class UserServiceApplication {

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

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

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

FeignClient의 name속성에 들어가는 값은 eureka 서버에 등록 돼 있는 Application 이름이다.

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

@GetMapping("/order-service/{userId}/orders")
List<ResponseOrder> getOrders(@PathVariable String userId);
}
@Override
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> orderList = orderServiceClient.getOrders(userId);
userDto.setOrders(orderList);

return userDto;
}
Share