반응형

Spring Cloud Feign?

  • Netflix에서 개발한 Http Client Binder이다
  • Feign을 사용하면 웹 서비스 클라이언트를 쉽게 작성할 수 있다
  • interface를 작성하고 annotation으로 선언하기만 하면 사용 가능하다
  • FeignClient는 스프링에서 사용하는 HttpMessageConverters를 사용하기 때문에 @PathVariable, @RequestParam, @RequestBody 같이 기존 스프링 어노테이션을 활용하여 사용할 수 있다.

Feign Client 프로젝트 설정

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>spring-msa-feign</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-msa-feign</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>11</java.version>
        <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
    </properties>

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

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>
@EnableFeignClients 어노테이션 설정
@EnableFeignClients
@SpringBootApplication
public class SpringMsaFeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringMsaFeignApplication.class, args);
    }
}
클라이언트 코드 작성
// demo.url = "http://localhost:8080"
@FeignClient(name = "demoClient", url = "${demo.url}")
public interface DemoClient {
    @GetMapping("/api/demo/{id}")
    Response getDemo(
        @PathVariable String id,
        @RequestHeader("token") String token,
        @RequestParam("name") String name
    );
}
코드 사용
@Slf4j
@SpringBootTest
public class DemoClientTest {
    @Autowired
    private DemoClient demoClient;

    @Test
    public void test_getDemo() throws IOException {
        Response response = demoClient.getDemo("1234", "auth-token", "john");
        log.info("{}", response.status());
        log.info("{}", response.body().asInputStream());
        log.info("{}", response.body().toString());
    }
}

사용법 코드 모음

// demo.url = "http://localhost:8080"
@FeignClient(name = "demoClient", url = "${demo.url}")
public interface DemoClient {
    @GetMapping("/api/demo/{id}")
    // @Cacheable(cacheNames = "demo-cache", key = "#param1 + #param2") // Application 클래스에 @EnableCaching 설정 필요
    Response getDemoV1(
        @PathVariable String id,
        @RequestHeader("token") String token,
        @RequestParam("name") String name
    );

    @GetMapping("/api/demo")
    String getDemoV2(
        @RequestHeader Map<String, String> headers,
        @RequestParam Map<String, String> params
    );

    @GetMapping("/api/demo")
    String getDemoV3(
        @SpringQueryMap DemoParams params
    );

    @PostMapping("/api/demo")
    String postDemoV1(
        @RequestBody String body
    );

    @PostMapping("/api/demo")
    String postDemoV2(
        @RequestBody DemoParams params
    );
}

Configuration

설명

  • FeignClient는 Java Config와 properties 방식으로 설정할 수 있다.
  • Java Config와 properties 모두 설정할 경우 Java Config 설정을 먼저 적용 후 properties 설정으로 override한다.
    • 위 기능 비활성화 하고싶다면 "feign.client.config.default-to-properties=false"로 설정한다.
  • FeignClient는 기본 설정으로 FeignClientsConfiguration을 바라본다.
    • FeignClientsConfiguration 설정 이후 사용자가 지정한 설정을 override 하는 방식.

properties로 설정하기

feign:
    client:
        config:
            default: # 전체 FeignClient에 적용
                connectTimeout: 5000    # 5초
                readTimeout: 5000       # 5초
            demoClient: # 개별 FeignClient에 적용(@FeignClient의 name 속성으로 입력한 값)
                connectionTimeout: 3000 # 3초
                readTimeout: 3000       # 3초

Java Config로 설정하기

// 전체 FeignClient 설정
@Configuration
public class FeignDefaultConfig {
    @Bean
    public Request.Options options() {
        return new Request.Options(5, TimeUnit.SECONDS, 5, TimeUnit.SECONDS, true);
    }
}
// 개별 FeignClient 설정
@FeignClient(name = "demoClient", url = "http://localhost:8080", configuration = DemoClient.Config.class)
public interface DemoClient {
    @GetMapping("/api/demo")
    String getDemo();

    class Config {
        @Bean
        public Request.Options options() {
            return new Request.Options(3, TimeUnit.SECONDS, 3, TimeUnit.SECONDS, true);
        }
    }
}

logging level 설정

# logging.level.{packagePath}.{className}
logging.level.com.example.demo_feign.client.DemoClient=DEBUG

logger level 설정

@Configuration
public class FeignDefaultConfig {
    @Bean
    public Logger.Level feignLoggerLevel() {
        /*
        NONE, No logging (DEFAULT).
        BASIC, Log only the request method and URL and the response status code and execution time.
        HEADERS, Log the basic information along with request and response headers.
        FULL, Log the headers, body, and metadata for both requests and responses.
        */
        return Logger.Level.FULL;
    }
}

참고

반응형

'Development > Spring' 카테고리의 다른 글

[Spring] Server Sent Event(SSE)  (0) 2021.03.30
[Spring] H2 Database  (0) 2021.02.27
[Spring] Spring Cloud Gateway  (0) 2020.12.27
[Spring] Spring Cloud Hystrix  (0) 2020.12.27
[Spring] Spring Cloud Eureka  (0) 2020.12.27

+ Recent posts