如何正確的使用Spring WebFlux?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
Spring WebFlux在內部使用Project Reactor及其發布者實現Flux和Mono。
新框架支持兩種編程模型:
基于注釋的反應元件
功能路由和處理
讓我們從spring boot starter webflux依賴項開始,它包含所有其他必需的依賴項:
spring boot和spring boot starter,用于基本的spring boot應用程序設置
spring-webflux框架
reactor-core我們需要的反應流,也需要reactor-netty
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> <version>2.2.6.RELEASE</version> </dependency>
我們現在將使用Spring WebFlux構建一個非常簡單的REST EmployeeManagement應用程序:
我們將使用一個簡單的域模型-帶有id和name字段的Employee
我們將使用RestController構建restapi,以將員工資源作為單個資源和集合發布
我們將使用WebClient構建一個客戶端來檢索相同的資源
我們將使用WebFlux和Spring Security創建一個安全的被動端點
springwebflux支持基于注釋的配置,方式與springwebmvc框架相同。
首先,在服務器上,我們創建一個帶注釋的控制器,它發布員工資源的反應流。
讓我們創建帶注釋的EmployeeController
:
@RestController @RequestMapping("/employees") public class EmployeeController { private final EmployeeRepository employeeRepository; // constructor... }
EmployeeRepository可以是任何支持非阻塞反應流的數據存儲庫。
讓我們在控制器中創建一個端點,用于發布單個員工資源:
@GetMapping("/{id}") private Mono<Employee> getEmployeeById(@PathVariable String id) { return employeeRepository.findEmployeeById(id); }
我們在Mono中包裝一個Employee資源,因為我們最多返回一個Employee。
我們還要添加一個端點來發布所有雇員的集合資源:
@GetMapping private Flux<Employee> getAllEmployees() { return employeeRepository.findAllEmployees(); }
對于集合資源,我們使用類型為Employee的流量,因為它是0..n元素的發布者。
Spring5中引入的WebClient是一個支持反應流的非阻塞客戶端。
我們可以使用WebClient創建一個客戶端,從EmployeeController提供的端點檢索數據。
讓我們創建一個簡單的EmployeeWebClient:
public class EmployeeWebClient { WebClient client = WebClient.create("http://localhost:8080"); // ... }
在這里,我們使用工廠方法create創建了一個WebClient。它會指向localhost:8080,所以我們可以使用或相對的URL來調用這個客戶端實例。
要從endpoint/employee/{id}檢索Mono類型的單個資源,請執行以下操作:
Mono<Employee> employeeMono = client.get() .uri("/employees/{id}", "1") .retrieve() .bodyToMono(Employee.class); employeeMono.subscribe(System.out::println);
類似地,要從endpoint/employees檢索Flux類型的集合資源,請執行以下操作:
Flux<Employee> employeeFlux = client.get() .uri("/employees") .retrieve() .bodyToFlux(Employee.class); employeeFlux.subscribe(System.out::println);
我們可以使用Spring Security來保護我們的反應端點。
假設我們在EmployeeController中有一個新的端點。此端點更新員工詳細信息并發回更新的員工。
由于這允許用戶更改現有員工,因此我們希望僅將此端點限制為管理員角色用戶。
讓我們為EmployeeController添加一個新方法:
@PostMapping("/update") private Mono<Employee> updateEmployee(@RequestBody Employee employee) { return employeeRepository.updateEmployee(employee); }
現在,為了限制對該方法的訪問,讓我們創建SecurityConfig并定義一些基于路徑的規則以僅允許管理員用戶:
@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(); } }
看完上述內容,你們掌握如何正確的使用Spring WebFlux的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。