5.3. WebFlux でのリアクティブ Spring Boot HTTP サービスの作成

Spring Boot および WebFlux を使用して、基本的なリアクティブ Hello World HTTP Web サービスを作成します。

前提条件

手順

  1. 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>

  2. アプリケーションのメインクラスを作成し、ルーターおよびハンドラーメソッドを定義します。

    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));
        }
    }

  3. オプション: アプリケーションをローカルで実行し、テストします。

    1. Maven プロジェクトのルートディレクトリーへ移動します。

      $ cd myApp
    2. アプリケーションをパッケージ化します。

      $ mvn clean package
    3. コマンドラインからアプリケーションを起動します。

      $ java -jar target/vertx-spring-boot-sample-http.jar
    4. 新しいターミナルウィンドウで、/hello エンドポイントで HTTP 要求を発行します。

      $ curl localhost:8080/hello
      Hello, World!
    5. カスタム名と、パーソナルな応答を取得するために要求を指定します。

      $ curl http://localhost:8080/hello?name=John
      Hello, John!

その他のリソース