Free Lines Arrow
본문 바로가기
Spring/Spring Cloud

[Spring Cloud] OpenFeign

by skahn1215 2023. 10. 21.
728x90
반응형

OpenFeign

  • netflex 에서 만든 Declarative(선언적인) HTTP Client 도구이다
  • Declarative(선언적인) 해당 용어의 표현은 어노테이션으로 선언을 하여 이를 구현할수 있다는 뜻으로 이해하면 쉬울것 같다.

 

OpenFeign 사용이유

  • 서비스 로직의 집중
     - 사용방법이 간편하다
    - 서비스 로직과 분리 할 수 있다.
  • 명시적인 표현
    - 어노테이션으로 명시적으로 선언하여 쉽게 사용용도를 파악 할 수 있다.
  • 간단한 코드 사용
    - Controller 처럼 인터페이스를 구현하여 깔끔하게 사용할수 있다.
    - Rest API 통신을 할때 Controller 를 구현하는 것처럼 사용할 수 있다.

 

OpenFeign 예제

  • 먼저 스프링 부트에 스프링 클라우드를 추가해 줘야 한다.
  • 단 버전을 잘 맞춰서 설치 해야 에러가 발생 하지 않는다.

의존성 추가하기

  • 아래 표를 보면 스프링 부트 3.0.x 버전에는 2022.0.x 릴리스가 호환성에 맞는 버전이라고 생각하면된다.

 

2022.0.3 릴리즈에 호환성 되는 목록이다.

  • Spring Cloud Starter Build 4.0.3 버전
  • Spring Cloud Openfeign 4.0.3 을 추가해 주자.

의존성 추가된 모습

plugins {
	id 'java'
	id 'org.springframework.boot' version '3.1.4'
	id 'io.spring.dependency-management' version '1.1.3'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
	sourceCompatibility = '17'
}

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
}

ext {
	set('springCloudVersion', "2022.0.3")
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-build
	implementation 'org.springframework.cloud:spring-cloud-starter-build:2022.0.3'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign
	implementation 'org.springframework.cloud:spring-cloud-starter-openfeign:4.0.3'
}


tasks.named('test') {
	useJUnitPlatform()
}

 

구현

  • 아래 어노테이션을 Application에 추가해 준다. 
@EnableFeignClients
package com.example.feign;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@SpringBootApplication
public class FeignApplication {

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

}

 

반응형

 

Feign client 구현

  • 보통 아래와 같은 경우는 GET을 사용하지만
  • 예제로 body 값을 넣기 위해 post 맵핑으로 만들었다.

 

User Controller

  • API 를 요청하기 위한 대상 컨트롤러 
package com.example.feign.controller;

import com.example.feign.Dto.UserDto;
import com.example.feign.feign.FeignUserClient;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.User;
import org.apache.catalina.util.ToStringUtil;
import org.apache.coyote.Request;
import org.apache.coyote.http11.upgrade.UpgradeServletOutputStream;
import org.apache.tomcat.util.descriptor.InputSourceUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor
@RestController
@RequestMapping("/v1/users")
public class UserController {
    @PostMapping("/{id}")
    public ResponseEntity<UserDto> findUserById(@RequestHeader HttpHeaders httpHeaders,
                                                @PathVariable(name = "id") String userId,
                                                @RequestBody(required = false) String body) {
        UserDto dto = new UserDto("test", "name");
        return new ResponseEntity<UserDto>(dto, HttpStatus.OK);
    }
}

 

728x90

Feign Controller

package com.example.feign.feign;

import com.example.feign.Dto.UserDto;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

@FeignClient(name = "UserClient", url = "http://localhost:8080")
public interface FeignUserClient {
    @PostMapping("/v1/users/{id}")
    ResponseEntity<UserDto> findUserId(@PathVariable(name = "id") String id, @RequestBody String body);
}

 

User Controller 에 요청을 하는 클라이언트

package com.example.feign.controller;

import com.example.feign.Dto.UserDto;
import com.example.feign.feign.FeignUserClient;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RequiredArgsConstructor
@RestController
@RequestMapping("/v1/users")
public class FeignController {

    private final FeignUserClient feignUserClient;

    @GetMapping("/test")
    public ResponseEntity<UserDto> test() {
        ResponseEntity<UserDto> test = feignUserClient.findUserId("123", "test");
        return test;
    }
}

 

결과

  • Feign 을 사용하여 UserController 의 user 정보를 가져왔다.

 

다음으로

  • Feign 사용법을 알았으니 이제 어떠한 기능들이 있는지 파악해본다
  • 다양한 예제를 가지고 Feign을 정복해 본다.
728x90
반응형

댓글