SpringBoot的另外一种模式WebFlux

mac2025-04-03  14

首先我们知道WebFlux是一个非阻塞的Web框架,它不再完全依赖于Servlet,默认推荐使用Netty异步容器。

创建一个处理方法类

package com.zcw.zcwwebflux.zcwwebflux.demmo; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; /** * @author zhaocunwei * @ClassName: HelloHandle * @Description: TODO * @date 2019/11/1 11:58 */ @Component public class HelloHandle { public Mono<ServerResponse> hello(ServerRequest request){ return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON) .body(BodyInserters.fromObject("hello zcw")); } }

创建一个Router类

用来定义路由信息,每个路由都会映射到对应的处理方法(功能类似于@RequestMapping)

package com.zcw.zcwwebflux.zcwwebflux.demmo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.reactive.function.server.RequestPredicates; import org.springframework.web.reactive.function.server.RouterFunction; import org.springframework.web.reactive.function.server.RouterFunctions; import org.springframework.web.reactive.function.server.ServerResponse; /** * @author zhaocunwei * @ClassName: HelloRuter * @Description: TODO * @date 2019/11/1 12:01 */ @Configuration public class HelloRuter { @Bean public RouterFunction<ServerResponse> routeHello(HelloHandle helloHandle){ return RouterFunctions .route(RequestPredicates.GET("/hello") .and(RequestPredicates.accept(MediaType.APPLICATION_JSON)), helloHandle ::hello); } }

测试

最新回复(0)