Spring×KotlinでOpenFeignを使う

はじめに

SpringBoot×KotlinでWebAPIを作る場合を想定して本記事を書きます。 WebAPIの中で別のAPIにアクセスするケースがあると思いますが その際のAPI clientとして、OpenFeignを使った実装をしてみたいと 思います。

環境構築

まずは実装のための環境構築をします。

前提

ここではintelijIDEAのコミュニティ版を使って行います。

Spring initializaで雛形作成

まずはプロジェクトの雛形を作成します。 以下にアクセスし、それぞれを入力するとプロジェクトの雛形が作成できます。 https://start.spring.io/

ここでは以下の感じで作成 f:id:set21set21:20200819235757p:plain

intelijIDEAで取り込み

よしなに作成した雛形を取り込みます。

実装

Controllerから

Controllerは以下のように実装。 ここではControllerから直接FeignClientを呼ぶことにします。

import com.example.demo.client.HelloClient
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class HelloController(
        private val client: HelloClient
) {
    @GetMapping("/hello")
    fun fetch(): String {
        return client.fetch()
    }
}

また今回はFeignのクライアントから呼び出すAPIを自前で用意することにし、 以下のようなControllerを作成します。

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class DummyController {
    @GetMapping("/dummy")
    fun dummy(): String {
        return "dummy"
    }
}

クライアント作成

今度はAPIを呼び出すクライアントを作成します。 OpenFeignを使うと、interfaceを定義するだけで呼び出すことができるので お手軽で良いですね。

import org.springframework.cloud.openfeign.FeignClient
import org.springframework.web.bind.annotation.GetMapping

@FeignClient(name = "HelloClient", url = "http://localhost:8080")
interface HelloClient {
    @GetMapping(value = ["dummy"])
    fun fetch(): String
}

動作確認

ローカル環境で動作確認をします。 ローカルでサーバを起動して以下のエンドポイントにアクセスします。

確認コマンド

curl http://localhost:8080/hello

結果

dummy

まとめ

OpenFeignを使って外部のAPIにアクセスするWebAPIの実装をしてみました。 interfaceを作成するだけで簡単に外部APIにアクセスする機能が実現できました。 ここではTimeoutなどの設定をしていませんが、そのような設定周りも実装してみたいと思います。

今回実装したものは以下にあります。 github.com