spring_boot_starter_feign

spring_boot_starter_feign は Spring for Dart に宣言的な HTTP クライアントを提供します。Spring Cloud OpenFeign に当たる Dart のものです。リモートの API を、エンドポイントごとに一つのメソッドを持ち、コントローラーと同じマッピングのアノテーションを使う抽象クラスとして記述します。他の Bean と同じようにそれを注入し、メソッドを呼べばリクエストが送られ、デコードされた応答が得られます。

使う理由

別のサービスを手で呼ぶには、エンドポイントごとに、URL を組み立て、JSON をエンコードし、リクエストを送り、ステータスを確認し、応答をデコードする必要があります。スターターがその部分を行います。

他のサービスを呼ぶサーバーや、バックエンドを呼ぶ Flutter アプリで使います。トランスポートは、VM と Flutter では dart:io、Web では fetch です。

セットアップ

# pubspec.yaml
dependencies:
  spring_boot_starter_feign: ^0.9.0

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0   # 必須: クライアントの実装を書く
  spring_boot_starter_test: ^0.9.0     # テストのための MockHttpTransport
  test: ^1.33.0

インポートは一つで足ります。package:spring_boot_starter_feign/spring_boot_starter_feign.dart は spring_boot_dart、spring_web_dart (マッピングのアノテーション)、spring_boot_starter_logging を再エクスポートします。

例

import 'package:spring_boot_starter_feign/spring_boot_starter_feign.dart';

import 'spring_gen/main.spring.dart';

// ショップが呼ぶ、カタログサービスの API。
@FeignClient('catalog', url: r'${catalog.url}')
abstract interface class CatalogClient {
  @GetMapping('/books/{isbn}')
  Future<Book> find(@PathVariable() String isbn);

  // GET /books?q=dune&page=2。page が null なら省かれる。
  @GetMapping('/books')
  Future<List<Book>> search(@RequestParam('q') String query, {@RequestParam() int? page});

  // 本は JSON として送られる。応答はステータスとヘッダーも返す。
  @PostMapping('/books')
  Future<ResponseEntity<Book>> create(@RequestBody() Book book);

  @DeleteMapping('/books/{isbn}')
  Future<void> delete(@PathVariable() String isbn);
}

class Book {
  const Book({required this.isbn, required this.title});

  final String isbn;
  final String title;
}

@Service()
class Shop {
  Shop(this.catalog);                 // 生成されたクライアント。他の Bean と同じく注入される

  final CatalogClient catalog;

  Future<String?> title(String isbn) async {
    try {
      return (await catalog.find(isbn)).title;
    } on FeignNotFound {
      return null;                    // ない本はショップにとってエラーではない
    }
  }
}

@SpringBootApplication()
void main(List<String> args) => runApplication(args);
# lib/resources/application.properties
catalog.url=https://api.neon.books
spring.feign.client.config.default.read-timeout=10s
spring.feign.client.config.catalog.logger-level=basic

クライアントのメソッドが受け取ったり返したりするクラスは、クライアントと同じパッケージにあれば、JSON のために自動的に記述されます。応答はそのコンストラクターとセッターで、引数はそのゲッターで記述されます。クラスに @Introspected() を付けると、すべてが記述されます。

起動するもの

内容

Spring (Java) との対応

@EnableFeignClients
@SpringBootApplication
class ShopApplication { ... }

@FeignClient(name = "catalog", url = "${catalog.url}")
interface CatalogClient {
  @GetMapping("/books/{isbn}")
  Book find(@PathVariable String isbn);
}

重要な違い:

関連項目