OpenFeignとは
RESTクライアントを簡単に作るためのフレームワークです
宣言的な REST クライアント: Feign は、JAX-RS または Spring MVC アノテーションで装飾されたインターフェースの動的実装を作成します
使い方
環境
Java11
Spring 2.6.1
OpenFeignのインストール
dependenciesに下記を追加します
build.gradle
dependencies {
// feign(HttpClient)
implementation("org.springframework.cloud:spring-cloud-starter-openfeign:3.1.0")
implementation("io.github.openfeign:feign-okhttp:11.7")
implementation("io.github.openfeign:feign-jackson:11.7")
implementation("io.github.openfeign:feign-slf4j:11.7")
}
OpenFeignを有効にする
Mainクラスに@EnableFeignClientsを付与してClientのコンポーネントスキャンを有効にします
SampleApplication.java
@SpringBootApplication
@EnableFeignClients
public class SampleApplication {
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
Feign Clientインターフェースの作成
configurationを宣言することで、既存コンポーネントをオーバーライドし、独自のエラーハンドリング等を行うことができます
作成したのはインターフェースですが、実装はFeignのフレームワークが勝手に作ってくれます
ServiceFoundationClient.java
@FeignClient(name = "serviceFoundation", url = "${service_foundation.server.url}", configuration = ServiceFoundationFeignConfiguration.class)
public interface ServiceFoundationClient {
/**
* サンプル
*/
@RequestMapping(method = RequestMethod.POST, value = "sample/api")
BaseResponseData sample(@RequestHeader(name = "Authorization") String token, @RequestHeader(name = "Content-Type") String contentType) throws AccessTokenExpiredException;
}
Clientを呼ぶ
ServiceFoundationApiRepositoryImpl.java
@Repository
@Slf4j
public class ServiceFoundationApiRepositoryImpl implements ServiceFoundationApiRepository {
private String CONTENT_TYPE = "application/json; charset=utf-8";
private final ServiceFoundationClient serviceFoundationClient;
public ServiceFoundationApiRepositoryImpl(ServiceFoundationClient serviceFoundationClient) {
this.serviceFoundationClient = serviceFoundationClient;
}
@Override
public BaseResponseData sample(String token) throws AccessTokenExpiredException {
BaseResponseData response = serviceFoundationClient.sample(token, CONTENT_TYPE);
if (StringUtil.isNotEmpty(response.getErrorCode())) {
//エラー時の処理
}
return response;
}
}
最後に
ご覧いただきありがとうございました
可読性が高く、非常に使いやすいですね
何かあればお気軽にコメントください