LoginSignup
2
1

More than 1 year has passed since last update.

spring-cloud-openfeignを使ってみた

Last updated at Posted at 2021-08-28
1 / 13

spring-cloud-openfeignとは?

ざっくり、
「最低限の実装でRestTemplateをもつClientクラスを提供してくれる」ライブラリです!


使い方

  1. 依存にspring-cloud-starter-openfeignを追加する
  2. FeignClientを有効化する
  3. FeignClientを実装する

1. 依存にspring-cloud-starter-openfeignを追加する

gradleの場合、build.gradleに以下のように記述します

...

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

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

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

2. FeignClientを有効化する

mainクラスに@EnableFeignClientsを付与します

@SpringBootApplication
@EnableFeignClients
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

3. FeignClientを実装する

@FeignClientを付与したinterfaceを作成します

@FeignClient(name = "sample", url = "http://localhost:8080")
public interface SampleClient {
    @GetMapping("/server/hello")
    String hello();
}

以上!!

これで、以下のような実装をしたのと同じです!

public SampleClient {
    private final RestTemplate restTemplate = new RestTemplateBuilder()
            .rootUri("http://localhost:8080")
            .build();

    public String hello() {
        return restTemplate.getForObject("/server/hello", String.class);
    }
}

ここからは、FeignClientについて踏み込んで見ていきます。


IFへの対応

@FeignClientを付与したinterfaceでは、RestControllerと同じようにIFを記述できます。


なので例えばパラメータを載せたい場合は@RequestParamを使えば良いし

    @GetMapping("/server/hello")
    String hello(@RequestParam String greeting);

ヘッダを載せたい場合は@RequestHeaderを使えば良い

    @GetMapping("/server/hello")
    String hello(@RequestHeader(value = "SAMPLE-HEADER") String header);

ヘッダを載せたいときはRestTemplateだと記述量が増えるのでありがたい…!


設定値の変更

propertyを記述することで実現できます。

ありがちなread timeoutとconnection timeoutだと、以下のような記述で設定ができます

application.yaml
feign:
  client:
    config:
      sample: # @FeignClient name
        connect-timeout: 1000 # milli seconds
        read-timeout:    5000 # milli seconds

interceptorの反映

RequestInterceptor(RestTemplateでいうClientHttpRequestInterceptor)を反映したい場合は、Bean登録しておくだけでOK!

ただ、Clientごとに適用するinterceptorを変えたいようなケースでは
専用のConfigurationクラスを作成してあげる方法もあります!


専用Configurationクラス
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;

//@Configuration // Configurationは不要
public class SampleConfig {
    @Bean
    public RequestInterceptor sampleRequestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                // 実装する
            }
        };
    }
}

作成したらFeignClientでConfigurationクラスを以下のように指定してあげればOK!

@FeignClient(name = "sample", url = "http://localhost:8080", configuration = SampleConfig.class)
public interface SampleClient {
    ...
}

他にもapplication.yamlでクラス指定をしてあげる方法もありますが、個人的にはConfigurationクラスを作るのがいいかなと

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1