Spring 5 WebFluxガイド

1概要

Spring WebFluxフレームワークはSpring 5の一部であり、Webアプリケーションにリアクティブプログラミングサポートを提供します。

このチュートリアルでは、リアクティブWebコンポーネント RestController と__WebClientを使用して、小さなリアクティブRESTアプリケーションを作成します。

また、Spring Securityを使用してリアクティブエンドポイントを保護する方法についても検討します。

2. Spring WebFluxフレームワーク

  • Spring WebFluxは内部でhttp://projectreactor.io/[Project Reactor]とそのパブリッシャーの実装を使っています - Flux そして Mono ** 。

新しいフレームワークは2つのプログラミングモデルをサポートします。

注釈ベースの反応コンポーネント

  • 機能的なルーティングと処理

ここでは、すでにhttps://www.baeldung.com/spring-5-functional-web[機能スタイル - ルーティングと処理]を検討したので、アノテーションベースのリアクティブコンポーネントに焦点を当てます。

3依存関係

spring-boot-starter-webflux 依存関係から始めましょう。実際には、他のすべての必要な依存関係が引き込まれています。

  • 基本のSpring Bootの場合は spring-boot spring-boot-starter

アプリケーション設定 ** __spring-webflux __framework

  • 私たちがリアクティブストリームに必要な リアクターコア__

反応者ネット

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <version>2.0.3.RELEASE</version>
</dependency>

最新のhttps://search.maven.org/classic/#search%7Cgav%7C1%7Cg%3A%22org.springframework.boot%22%20AND%20a%3A%22spring-boot-starter-webflux%22[spring -boot-starter-webflux]はMaven Centralからダウンロードできます。

4.リアクティブRESTアプリケーション

Spring WebFluxを使用して、非常に単純なReactive REST EmployeeManagement アプリケーションを構築します。**

  • 単純なドメインモデルを使用します - Employee id および name

フィールド ** 公開用のREST APIを作成し、SingleだけでなくSingleも取得します。

_RestControllerを使用した Employee リソースの収集 and WebClient_ ** そして、WebFluxを使用して安全なリアクティブエンドポイントも作成します。

と春のセキュリティ

5.反応性 RestController

Spring WebFluxはSpring Web MVCフレームワークと同じ方法でアノテーションベースの設定をサポートします。

まずサーバー側で、私たちは Employee 。** のリアクティブストリームを公開するアノテーション付きコントローラーを作成します。

注釈付きの EmployeeController を作成しましょう。

@RestController
@RequestMapping("/employees")
public class EmployeeReactiveController {

    private final EmployeeRepository employeeRepository;

   //constructor...
}

__EmployeeRepository __は、ノンブロッキングリアクティブストリームをサポートする任意のデータリポジトリです。

5.1. 単一リソース

単一の__Employeeリソースを公開するエンドポイントをコントローラに作成しましょう。

@GetMapping("/{id}")
private Mono<Employee> getEmployeeById(@PathVariable String id) {
    return employeeRepository.findEmployeeById(id);
}
  • 単一の Employee リソースについては、最大1つの要素を発行するため、 Employee タイプの Mono を使用しました。

5.2. 収集リソース

すべての Employees のコレクションリソースを公開するエンドポイントをコントローラに追加しましょう。

@GetMapping
private Flux<Employee> getAllEmployees() {
    return employeeRepository.findAllEmployees();
}
  • コレクションリソースには、 Employee タイプの Flux を使用しました - それは、パブリッシャーが 0 . 。n要素の発行に焦点を当てていたためです。

6.反応性Webクライアント

Spring 5で導入されたhttps://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-client[ WebClient ]は、Reactive Streamsをサポートするノンブロッキングクライアントです。

  • クライアント側では、 EmployeeControllerで作成されたエンドポイントからデータを取得するために WebClient__を使用します。

簡単な EmployeeWebClient を作成しましょう。

public class EmployeeWebClient {

    WebClient client = WebClient.create("http://localhost:8080");

   //...
}

ここでは、ファクトリメソッド create を使って WebClient を作成しました。

相対URLについては、 __ localhost:8080を参照してください。

6.1. 単一リソースの取得

エンドポイント /employee/\ {id} から Mono タイプの単一リソースを取得するには、次の手順を実行します。

Mono<Employee> employeeMono = client.get()
  .uri("/employees/{id}", "1")
  .retrieve()
  .bodyToMono(Employee.class);

employeeMono.subscribe(System.out::println);

6.2. コレクションリソースの取得

同様に、エンドポイント /employees からタイプ Flux のコレクションリソースを取得するには、次の手順を実行します。

Flux<Employee> employeeFlux = client.get()
  .uri("/employees")
  .retrieve()
  .bodyToFlux(Employee.class);

employeeFlux.subscribe(System.out::println);

WebClientの設定と操作 についての詳細な記事もあります。 _. _

7. Spring WebFluxのセキュリティ

Spring Securityを使用してリアクティブエンドポイントを保護することができます。

__EmployeeControllerに新しいエンドポイントがあるとします。 このエンドポイントは Employee 詳細を更新し、更新された Employeeを返送します。

これによりユーザーは既存の従業員を変更できますので、このエンドポイントを ADMIN ロールユーザーのみに制限します。

EmployeeController に新しいメソッドを追加しましょう。

@PostMapping("/update")
private Mono<Employee> updateEmployee(@RequestBody Employee employee) {
    return employeeRepository.updateEmployee(employee);
}

では、このメソッドへのアクセスを制限するために SecurityConfig を作成し、ADMINユーザーのみを許可するようにパスベースのルールをいくつか定義しましょう。

@EnableWebFluxSecurity
public class EmployeeWebSecurityConfig {

   //...

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(
      ServerHttpSecurity http) {
        http.csrf().disable()
          .authorizeExchange()
          .pathMatchers(HttpMethod.POST, "/employees/update").hasRole("ADMIN")
          .pathMatchers("/** ** ").permitAll()
          .and()
          .httpBasic();
        return http.build();
    }
}

この設定はエンドポイント /employees/update へのアクセスを制限します。したがって、ロール ADMIN を持つユーザーのみがこのエンドポイントにアクセスして既存の__Employeeを更新できます。

最後に、注釈 __ @ EnableWebFluxSecurity __がSpring Security WebFluxをいくつかのデフォルト設定でサポートします。

Spring WebFluxセキュリティの設定と操作 に関する詳細な記事もあります。

8.まとめ

この記事では、小さなReactive RESTアプリケーションを作成することによって、Spring WebFluxフレームワークでサポートされているReactive Webコンポーネントを作成して操作する方法について説明しました。

RestController および __WebClient __を使用して、反応型ストリームをそれぞれ公開および消費する方法を学びました。

また、Spring Securityの助けを借りて、セキュアなリアクティブエンドポイントを作成する方法も調べました。

Reactive RestController および WebClientの他に、WebFlux フレームワークはReactive Streamのソケットスタイルのストリーミング用に反応型 WebSocket および対応する WebSocketClient もサポートします。

Spring 5でのReactive WebSocketの使用 に焦点を当てた詳細な記事があります。

最後に、このチュートリアルで使用されている完全なソースコードはhttps://github.com/eugenp/tutorials/tree/master/spring-5-reactive-security[Githubでさらに入手]です。