RouterFunction模式服务

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的请求和响应对象。

作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。
Copyright © 2017-2024 Gacfox All Rights Reserved.
Build with NextJS | Sitemap