SpringBoot(一)Spring WebFlux使用
阿新 • • 發佈:2018-12-04
Spring WebFlux定義
Spring WebFlux是隨著Spring 5.0版本推出來的響應式Web框架,它與SpringMVC的區別是不需要ServletAPI,完全是一種非同步非阻塞的Web框架。非阻塞方式可以利用較小的執行緒或者硬體資源實現高併發進而提供系統性能,因為Spring5.0以後必須使用Java8函數語言程式設計風格,而且Spring WebFlux支援Java8的函數語言程式設計風格。
新增POM依賴
<!--如果pom檔案有spring-boot-starter-web支援,一定要註釋掉,因為不註釋掉預設的還是SpringMvc而不是WebFlux--> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> --> <!--WebFlux依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
編寫程式碼
package com.lyz.project.controller; import com.lyz.project.entity.MyConfigBean; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; /** * 類的註釋 * * @Package com.lyz.project.controller * @ClassName UserWebFluxController * @Description * @Author liyuzhi * @Date 2018-11-12 19:26 */ @Component public class UserWebFluxController { private final MyConfigBean myConfigBean; public UserWebFluxController(MyConfigBean myConfigBean) { this.myConfigBean = myConfigBean; } public Mono<ServerResponse> queryUser(ServerRequest request) { myConfigBean.setUsername("queryUser"); Mono<MyConfigBean> myConfigBeanMono = Mono.just(myConfigBean); return ServerResponse.ok().body(myConfigBeanMono, MyConfigBean.class); } public Mono<ServerResponse> delUser(ServerRequest request) { myConfigBean.setUsername("delUser"); Mono<MyConfigBean> myConfigBeanMono = Mono.just(myConfigBean); return ServerResponse.ok().body(myConfigBeanMono, MyConfigBean.class); } }
package com.lyz.project.web; import com.lyz.project.controller.UserWebFluxController; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.ServerResponse; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.web.reactive.function.server.RequestPredicates.GET; import static org.springframework.web.reactive.function.server.RequestPredicates.accept; import static org.springframework.web.reactive.function.server.RouterFunctions.route; /** * 類的註釋 * * @Package com.lyz.project.web * @ClassName MyBeanConfigRouter * @Description * @Author liyuzhi * @Date 2018-11-12 19:35 */ @Configuration public class MyBeanConfigRouter { @Bean public RouterFunction<ServerResponse> monoRouterFunction(UserWebFluxController userWebFluxController) { return route(GET("/getUser").and(accept(APPLICATION_JSON)), userWebFluxController::queryUser) .andRoute(GET(("/delUser")).and(accept(APPLICATION_JSON)), userWebFluxController::delUser); } }