Panduan untuk Spring 5 WebFlux

1. Gambaran keseluruhan

Spring WebFlux adalah sebahagian daripada Spring 5 dan memberikan sokongan pengaturcaraan reaktif untuk aplikasi web.

Dalam tutorial ini, kita akan membuat aplikasi REST reaktif kecil menggunakan komponen web reaktif RestController dan WebClient.

Kami juga akan melihat bagaimana mendapatkan titik akhir reaktif kami menggunakan Spring Security.

2. Rangka Kerja Spring WebFlux

Spring WebFlux secara dalaman menggunakan Project Reactor dan pelaksanaan penerbitnya - Flux dan Mono .

Rangka kerja baru menyokong dua model pengaturcaraan:

  • Komponen reaktif berasaskan anotasi
  • Penghalaan dan pengendalian yang berfungsi

Kami akan memfokuskan pada komponen reaktif berasaskan anotasi, kerana kami sudah meneroka gaya fungsional - penghalaan dan pengendalian dalam tutorial lain.

3. Kebergantungan

Mari kita mulakan dengan pergantungan spring-boot-starter-webflux , yang menggunakan semua kebergantungan lain yang diperlukan:

  • spring-boot dan spring-boot-starter untuk persediaan aplikasi Spring Boot asas
  • rangka kerja spring-webflux
  • inti reaktor yang kita perlukan untuk aliran reaktif dan juga jaring reaktor
 org.springframework.boot spring-boot-starter-webflux 2.2.6.RELEASE 

Fluks spring-boot-starter-webflux terkini boleh dimuat turun dari Maven Central.

4. Aplikasi REST Reaktif

Kami sekarang akan membina aplikasi Pengurusan Karyawan REST reaktif yang sangat sederhana - menggunakan Spring WebFlux:

  • Kami akan menggunakan model domain sederhana - Kakitangan dengan id dan bidang nama
  • Kami akan membina REST API dengan RestController untuk menerbitkan sumber pekerja sebagai sumber tunggal dan sebagai koleksi
  • Kami akan membina klien dengan WebClient untuk mendapatkan sumber yang sama
  • Kami akan membuat titik akhir reaktif yang selamat menggunakan WebFlux dan Spring Security

5. Pengawal Rehat Reaktif

Spring WebFlux menyokong konfigurasi berasaskan anotasi dengan cara yang sama seperti rangka Web MVC Spring.

Sebagai permulaan, di pelayan, kami membuat pengawal beranotasi yang menerbitkan aliran reaktif sumber pekerja .

Mari buat kami beranotasi EmployeeController :

@RestController @RequestMapping("/employees") public class EmployeeController { private final EmployeeRepository employeeRepository; // constructor... }

EmployeeRepository boleh menjadi repositori data yang menyokong aliran reaktif yang tidak menyekat.

5.1. Sumber Tunggal

Mari buat titik akhir dalam pengawal kami yang menerbitkan satu sumber Pekerja :

@GetMapping("/{id}") private Mono getEmployeeById(@PathVariable String id) { return employeeRepository.findEmployeeById(id); }

Kami membungkus satu sumber Pekerja dengan Mono kerana kami mengembalikan paling banyak seorang pekerja.

5.2. Sumber Pengumpulan

Mari juga tambahkan titik akhir yang menerbitkan sumber pengumpulan semua Kakitangan :

@GetMapping private Flux getAllEmployees() { return employeeRepository.findAllEmployees(); }

Untuk sumber pengumpulan, kami menggunakan Flux jenis Pekerja - kerana itulah penerbit untuk elemen 0. .n.

6. Pelanggan Web Reaktif

WebClient introduced in Spring 5 is a non-blocking client with support for reactive streams.

We can use WebClient to create a client to retrieve data from the endpoints provided by the EmployeeController.

Let's create a simple EmployeeWebClient:

public class EmployeeWebClient { WebClient client = WebClient.create("//localhost:8080"); // ... }

Here we have created a WebClient using its factory method create. It'll point to localhost:8080 so we can use or relative URLs for calls made by this client instance.

6.1. Retrieving a Single Resource

To retrieve single resource of type Mono from endpoint /employee/{id}:

Mono employeeMono = client.get() .uri("/employees/{id}", "1") .retrieve() .bodyToMono(Employee.class); employeeMono.subscribe(System.out::println);

6.2. Retrieving a Collection Resource

Similarly, to retrieve a collection resource of type Flux from endpoint /employees:

Flux employeeFlux = client.get() .uri("/employees") .retrieve() .bodyToFlux(Employee.class); employeeFlux.subscribe(System.out::println);

We also have a detailed article on setting up and working with WebClient.

7. Spring WebFlux Security

We can use Spring Security to secure our reactive endpoints.

Let's suppose we have a new endpoint in our EmployeeController. This endpoint updates Employee details and sends back the updated Employee.

Since this allows users to change existing employees, we want to restrict this endpoint to ADMIN role users only.

Let's add a new method to our EmployeeController:

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

Now, to restrict access to this method let's create SecurityConfig and define some path-based rules to only allow ADMIN users:

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

This configuration will restrict access to the endpoint /employees/update. Therefore only users having a role ADMIN will be able to access this endpoint and update an existing Employee.

Finally, the annotation @EnableWebFluxSecurity adds Spring Security WebFlux support with some default configurations.

We also have a detailed article on configuring and working with Spring WebFlux security.

8. Conclusion

In this article, we've explored how to create and work with reactive web components as supported by the Spring WebFlux framework. As an example, we've built a small Reactive REST application.

We learned how to use RestController and WebClient to publish and consume reactive streams.

We also looked into how to create a secured reactive endpoint with the help of Spring Security.

Other than Reactive RestController and WebClient, the WebFlux framework also supports reactive WebSocket and the corresponding WebSocketClient for socket style streaming of Reactive Streams.

We have a detailed article focused on working with Reactive WebSocket with Spring 5.

Akhirnya, kod sumber lengkap yang digunakan dalam tutorial ini terdapat di Github.