5.3. WebFlux でのリアクティブ Spring Boot HTTP サービスの作成
Spring Boot および WebFlux を使用して、基本的なリアクティブ Hello World HTTP Web サービスを作成します。
前提条件
- JDK 8 または JDK 11 がインストールされている。
- Maven がインストールされている。
- Spring Boot を使用するよう設定されたMaven ベースのアプリケーションプロジェクト
手順
vertx-spring-boot-starter-http
をプロジェクトのpom.xml
ファイルに依存関係として追加します。pom.xml
<project> ... <dependencies> ... <dependency> <groupId>dev.snowdrop</groupId> <artifactId>vertx-spring-boot-starter-http</artifactId> </dependency> ... <dependencies> ... </project>
アプリケーションのメインクラスを作成し、ルーターおよびハンドラーメソッドを定義します。
HttpSampleApplication.java
package dev.snowdrop.vertx.sample.http; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; import static org.springframework.web.reactive.function.BodyInserters.fromObject; import static org.springframework.web.reactive.function.server.RouterFunctions.route; import static org.springframework.web.reactive.function.server.ServerResponse.ok; @SpringBootApplication public class HttpSampleApplication { public static void main(String[] args) { SpringApplication.run(HttpSampleApplication.class, args); } @Bean public RouterFunction<ServerResponse> helloRouter() { return route() .GET("/hello", this::helloHandler) .build(); } private Mono<ServerResponse> helloHandler(ServerRequest request) { String name = request .queryParam("name") .orElse("World"); String message = String.format("Hello, %s!", name); return ok() .body(fromObject(message)); } }
オプション: アプリケーションをローカルで実行し、テストします。
Maven プロジェクトのルートディレクトリーへ移動します。
$ cd myApp
アプリケーションをパッケージ化します。
$ mvn clean package
コマンドラインからアプリケーションを起動します。
$ java -jar target/vertx-spring-boot-sample-http.jar
新しいターミナルウィンドウで、
/hello
エンドポイントで HTTP 要求を発行します。$ curl localhost:8080/hello Hello, World!
カスタム名と、パーソナルな応答を取得するために要求を指定します。
$ curl http://localhost:8080/hello?name=John Hello, John!
その他のリソース
- Fabric8 Maven プラグインを使用して、アプリケーションを OpenShift クラスターにデプロイ できます。
- また、スタンドアロンの Red Hat Enterprise Linux でのデプロイメント 用にアプリケーションを設定することもできます。
- Spring Boot でリアクティブ Web サービスの作成に関する詳細は、Spring コミュニティードキュメントの リアクティブ REST サービスの開発ガイド を参照してください。