SpringWebFlux中,除了使用传统的Controller写法,还可以使用RouterFunction实现请求响应处理。RouterFunction的写法更加抽象,但其优势是函数式写法,可以将所有的路由匹配写在同一个位置,可以利用闭包等特性简化代码。
下面例子中,我们基于RouterFunction编写了一个请求响应处理流程。
package com.gacfox.demo.config;
import com.gacfox.demo.model.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import reactor.core.publisher.Mono;
@Configuration
public class DemoRouterConfiguration {
@Bean
public RouterFunction<ServerResponse> routerConfiguration() {
return RouterFunctions.route(
RequestPredicates.GET("/getStudent"),
(request) -> {
Student s = Student.builder()
.studentId("001").name("Tom").age(18).score("A")
.build();
Mono<Student> mono = Mono.just(s);
return ServerResponse.ok().body(mono, Student.class);
}
);
}
}
RouterFunctions.route()
的方法签名如下:
public static <T extends ServerResponse> RouterFunction<T> route(RequestPredicate predicate, HandlerFunction<T> handlerFunction)
其中predicate
封装了请求的方法、路由等,我们可以理解为它是一个断言,满足断言的请求才会接收处理;handlerFunction
就是具体的请求处理逻辑函数,它接收参数ServerRequest
返回ServerResponse
,分别代表HTTP的请求和响应对象。