Spring WebFlux 包括 WebFlux.fn,这是一个轻量级函数式编程模型,其中函数 用于路由和处理请求,而 Contract 旨在实现不变性。 它是基于 Comments 的编程模型的替代方案,但在其他方面运行 相同的 Reactive Core 基础。
概述
在 WebFlux.fn 中,HTTP 请求使用 : 处理,该函数接受并返回延迟(即 )。
请求和响应对象都有不可变的契约,这些契约提供对 JDK 8 友好的
访问 HTTP 请求和响应。 等效于
基于注释的编程模型。HandlerFunctionServerRequestServerResponseMono<ServerResponse>HandlerFunction@RequestMapping
传入请求被路由到具有 : 的处理程序函数,该函数
接受并返回一个延迟的(即 )。
当 router 函数匹配时,将返回一个处理程序函数;否则为空 Mono。 等同于注释,但使用 major
不同之处在于 router 函数不仅提供数据,还提供行为。RouterFunctionServerRequestHandlerFunctionMono<HandlerFunction>RouterFunction@RequestMapping
RouterFunctions.route()提供便于创建路由器的 Router 构建器,
如下例所示:
- 
Java
 - 
Kotlin
 
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
PersonRepository repository = ...
PersonHandler handler = new PersonHandler(repository);
RouterFunction<ServerResponse> route = route() (1)
	.GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson)
	.GET("/person", accept(APPLICATION_JSON), handler::listPeople)
	.POST("/person", handler::createPerson)
	.build();
public class PersonHandler {
	// ...
	public Mono<ServerResponse> listPeople(ServerRequest request) {
		// ...
	}
	public Mono<ServerResponse> createPerson(ServerRequest request) {
		// ...
	}
	public Mono<ServerResponse> getPerson(ServerRequest request) {
		// ...
	}
}
| 1 | 使用 创建路由器。route() | 
val repository: PersonRepository = ...
val handler = PersonHandler(repository)
val route = coRouter { (1)
	accept(APPLICATION_JSON).nest {
		GET("/person/{id}", handler::getPerson)
		GET("/person", handler::listPeople)
	}
	POST("/person", handler::createPerson)
}
class PersonHandler(private val repository: PersonRepository) {
	// ...
	suspend fun listPeople(request: ServerRequest): ServerResponse {
		// ...
	}
	suspend fun createPerson(request: ServerRequest): ServerResponse {
		// ...
	}
	suspend fun getPerson(request: ServerRequest): ServerResponse {
		// ...
	}
}
| 1 | 使用 Coroutines router DSL 创建 router;反应式替代方案也可通过以下方式获得。router { } | 
运行 a 的一种方法是将其转换为 an 并安装它
通过其中一个内置服务器适配器:RouterFunctionHttpHandler
- 
RouterFunctions.toHttpHandler(RouterFunction) - 
RouterFunctions.toHttpHandler(RouterFunction, HandlerStrategies) 
大多数应用程序可以通过 WebFlux Java 配置运行,请参阅运行服务器。
| 1 | 使用 创建路由器。route() | 
| 1 | 使用 Coroutines router DSL 创建 router;反应式替代方案也可通过以下方式获得。router { } | 
HandlerFunction 函数
ServerRequest并且是提供 JDK 8 友好的不可变接口
访问 HTTP 请求和响应。
请求和响应都提供 Reactive Streams 背压
与身体流相反。
请求正文用 Reactor 或 表示。
响应正文由任何 Reactive Streams 表示,包括 和 。
有关更多信息,请参阅 反应式库。ServerResponseFluxMonoPublisherFluxMono
服务器请求
ServerRequest提供对 HTTP 方法、URI、标头和查询参数的访问,
而对 body 的访问是通过 methods.body
以下示例将请求正文提取为 :Mono<String>
- 
Java
 - 
Kotlin
 
Mono<String> string = request.bodyToMono(String.class);
val string = request.awaitBody<String>()
以下示例将正文提取为 a(或 Kotlin 中的 a),
其中,对象是从某种序列化形式(例如 JSON 或 XML)解码的:Flux<Person>Flow<Person>Person
- 
Java
 - 
Kotlin
 
Flux<Person> people = request.bodyToFlux(Person.class);
val people = request.bodyToFlow<Person>()
前面的示例是使用更通用的 、
它接受函数式策略接口。Utility 类提供对许多实例的访问。例如,前面的示例可以
也写成如下:ServerRequest.body(BodyExtractor)BodyExtractorBodyExtractors
- 
Java
 - 
Kotlin
 
Mono<String> string = request.body(BodyExtractors.toMono(String.class));
Flux<Person> people = request.body(BodyExtractors.toFlux(Person.class));
	val string = request.body(BodyExtractors.toMono(String::class.java)).awaitSingle()
	val people = request.body(BodyExtractors.toFlux(Person::class.java)).asFlow()
以下示例显示如何访问表单数据:
- 
Java
 - 
Kotlin
 
Mono<MultiValueMap<String, String>> map = request.formData();
val map = request.awaitFormData()
以下示例显示如何以 map 形式访问多部分数据:
- 
Java
 - 
Kotlin
 
Mono<MultiValueMap<String, Part>> map = request.multipartData();
val map = request.awaitMultipartData()
以下示例显示如何以流式处理方式访问分段数据(一次一个):
- 
Java
 - 
Kotlin
 
Flux<PartEvent> allPartEvents = request.bodyToFlux(PartEvent.class);
allPartsEvents.windowUntil(PartEvent::isLast)
      .concatMap(p -> p.switchOnFirst((signal, partEvents) -> {
          if (signal.hasValue()) {
              PartEvent event = signal.get();
              if (event instanceof FormPartEvent formEvent) {
                  String value = formEvent.value();
                  // handle form field
              }
              else if (event instanceof FilePartEvent fileEvent) {
                  String filename = fileEvent.filename();
                  Flux<DataBuffer> contents = partEvents.map(PartEvent::content);
                  // handle file upload
              }
              else {
                  return Mono.error(new RuntimeException("Unexpected event: " + event));
              }
          }
          else {
              return partEvents; // either complete or error signal
          }
      }));
val parts = request.bodyToFlux<PartEvent>()
allPartsEvents.windowUntil(PartEvent::isLast)
    .concatMap {
        it.switchOnFirst { signal, partEvents ->
            if (signal.hasValue()) {
                val event = signal.get()
                if (event is FormPartEvent) {
                    val value: String = event.value();
                    // handle form field
                } else if (event is FilePartEvent) {
                    val filename: String = event.filename();
                    val contents: Flux<DataBuffer> = partEvents.map(PartEvent::content);
                    // handle file upload
                } else {
                    return Mono.error(RuntimeException("Unexpected event: " + event));
                }
            } else {
                return partEvents; // either complete or error signal
            }
        }
    }
}
请注意,对象的正文内容必须完全使用、中继或释放,以避免内存泄漏。PartEvent
服务器响应
ServerResponse提供对 HTTP 响应的访问,并且由于它是不可变的,因此您可以使用
一个创建它的方法。您可以使用生成器设置响应状态,以添加响应
headers 或提供正文。以下示例使用 JSON 创建 200 (OK) 响应
内容:build
- 
Java
 - 
Kotlin
 
Mono<Person> person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(person, Person.class);
val person: Person = ...
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(person)
以下示例显示如何构建带有标头但无正文的 201 (CREATED) 响应:Location
- 
Java
 - 
Kotlin
 
URI location = ...
ServerResponse.created(location).build();
val location: URI = ...
ServerResponse.created(location).build()
根据所使用的编解码器,可以传递 hint 参数来自定义 body 是序列化的或反序列化的。例如,要指定 Jackson JSON 视图:
- 
Java
 - 
Kotlin
 
ServerResponse.ok().hint(Jackson2CodecSupport.JSON_VIEW_HINT, MyJacksonView.class).body(...);
ServerResponse.ok().hint(Jackson2CodecSupport.JSON_VIEW_HINT, MyJacksonView::class.java).body(...)
处理程序类
我们可以将处理程序函数编写为 lambda,如下例所示:
- 
Java
 - 
Kotlin
 
HandlerFunction<ServerResponse> helloWorld =
  request -> ServerResponse.ok().bodyValue("Hello World");
val helloWorld = HandlerFunction<ServerResponse> { ServerResponse.ok().bodyValue("Hello World") }
这很方便,但在应用程序中,我们需要多个函数和多个内联
Lambda 可能会变得混乱。
因此,将相关的处理程序函数一起分组到一个处理程序类中是很有用的,该
具有与基于注释的应用程序类似的角色。
例如,以下类公开了一个反应式存储库:@ControllerPerson
- 
Java
 - 
Kotlin
 
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.ServerResponse.ok;
public class PersonHandler {
	private final PersonRepository repository;
	public PersonHandler(PersonRepository repository) {
		this.repository = repository;
	}
	public Mono<ServerResponse> listPeople(ServerRequest request) { (1)
		Flux<Person> people = repository.allPeople();
		return ok().contentType(APPLICATION_JSON).body(people, Person.class);
	}
	public Mono<ServerResponse> createPerson(ServerRequest request) { (2)
		Mono<Person> person = request.bodyToMono(Person.class);
		return ok().build(repository.savePerson(person));
	}
	public Mono<ServerResponse> getPerson(ServerRequest request) { (3)
		int personId = Integer.valueOf(request.pathVariable("id"));
		return repository.getPerson(personId)
			.flatMap(person -> ok().contentType(APPLICATION_JSON).bodyValue(person))
			.switchIfEmpty(ServerResponse.notFound().build());
	}
}
| 1 | listPeople是一个处理程序函数,它将在存储库中找到的所有对象作为
JSON 的 JSON 格式。Person | 
| 2 | createPerson是一个处理程序函数,用于存储请求正文中包含的 new。
请注意,返回 : 一个发出
从请求中读取并存储人员时的完成信号。因此,我们使用该方法在收到该完成信号时发送响应(即
当 已保存时)。PersonPersonRepository.savePerson(Person)Mono<Void>Monobuild(Publisher<Void>)Person | 
| 3 | getPerson是一个处理程序函数,它返回一个 person,由路径
变量。我们从存储库中检索该响应并创建一个 JSON 响应(如果是
发现。如果未找到,我们将返回 404 Not Found 响应。idPersonswitchIfEmpty(Mono<T>) | 
class PersonHandler(private val repository: PersonRepository) {
	suspend fun listPeople(request: ServerRequest): ServerResponse { (1)
		val people: Flow<Person> = repository.allPeople()
		return ok().contentType(APPLICATION_JSON).bodyAndAwait(people);
	}
	suspend fun createPerson(request: ServerRequest): ServerResponse { (2)
		val person = request.awaitBody<Person>()
		repository.savePerson(person)
		return ok().buildAndAwait()
	}
	suspend fun getPerson(request: ServerRequest): ServerResponse { (3)
		val personId = request.pathVariable("id").toInt()
		return repository.getPerson(personId)?.let { ok().contentType(APPLICATION_JSON).bodyValueAndAwait(it) }
				?: ServerResponse.notFound().buildAndAwait()
	}
}
| 1 | listPeople是一个处理程序函数,它将在存储库中找到的所有对象作为
JSON 的 JSON 格式。Person | 
| 2 | createPerson是一个处理程序函数,用于存储请求正文中包含的 new。
请注意,这是一个没有返回类型的 suspending 函数。PersonPersonRepository.savePerson(Person) | 
| 3 | getPerson是一个处理程序函数,它返回一个 person,由路径
变量。我们从存储库中检索该响应并创建一个 JSON 响应(如果是
发现。如果未找到,我们将返回 404 Not Found 响应。idPerson | 
验证
- 
Java
 - 
Kotlin
 
public class PersonHandler {
	private final Validator validator = new PersonValidator(); (1)
	// ...
	public Mono<ServerResponse> createPerson(ServerRequest request) {
		Mono<Person> person = request.bodyToMono(Person.class).doOnNext(this::validate); (2)
		return ok().build(repository.savePerson(person));
	}
	private void validate(Person person) {
		Errors errors = new BeanPropertyBindingResult(person, "person");
		validator.validate(person, errors);
		if (errors.hasErrors()) {
			throw new ServerWebInputException(errors.toString()); (3)
		}
	}
}
| 1 | Create instance 创建实例。Validator | 
| 2 | 应用验证。 | 
| 3 | 引发 400 响应的异常。 | 
class PersonHandler(private val repository: PersonRepository) {
	private val validator = PersonValidator() (1)
	// ...
	suspend fun createPerson(request: ServerRequest): ServerResponse {
		val person = request.awaitBody<Person>()
		validate(person) (2)
		repository.savePerson(person)
		return ok().buildAndAwait()
	}
	private fun validate(person: Person) {
		val errors: Errors = BeanPropertyBindingResult(person, "person");
		validator.validate(person, errors);
		if (errors.hasErrors()) {
			throw ServerWebInputException(errors.toString()) (3)
		}
	}
}
| 1 | Create instance 创建实例。Validator | 
| 2 | 应用验证。 | 
| 3 | 引发 400 响应的异常。 | 
处理程序还可以通过创建和注入来使用标准 bean 验证 API (JSR-303)
基于 的全局实例。
参见 Spring Validation。ValidatorLocalValidatorFactoryBean
| 1 | listPeople是一个处理程序函数,它将在存储库中找到的所有对象作为
JSON 的 JSON 格式。Person | 
| 2 | createPerson是一个处理程序函数,用于存储请求正文中包含的 new。
请注意,返回 : 一个发出
从请求中读取并存储人员时的完成信号。因此,我们使用该方法在收到该完成信号时发送响应(即
当 已保存时)。PersonPersonRepository.savePerson(Person)Mono<Void>Monobuild(Publisher<Void>)Person | 
| 3 | getPerson是一个处理程序函数,它返回一个 person,由路径
变量。我们从存储库中检索该响应并创建一个 JSON 响应(如果是
发现。如果未找到,我们将返回 404 Not Found 响应。idPersonswitchIfEmpty(Mono<T>) | 
| 1 | listPeople是一个处理程序函数,它将在存储库中找到的所有对象作为
JSON 的 JSON 格式。Person | 
| 2 | createPerson是一个处理程序函数,用于存储请求正文中包含的 new。
请注意,这是一个没有返回类型的 suspending 函数。PersonPersonRepository.savePerson(Person) | 
| 3 | getPerson是一个处理程序函数,它返回一个 person,由路径
变量。我们从存储库中检索该响应并创建一个 JSON 响应(如果是
发现。如果未找到,我们将返回 404 Not Found 响应。idPerson | 
| 1 | Create instance 创建实例。Validator | 
| 2 | 应用验证。 | 
| 3 | 引发 400 响应的异常。 | 
| 1 | Create instance 创建实例。Validator | 
| 2 | 应用验证。 | 
| 3 | 引发 400 响应的异常。 | 
RouterFunction
Router 函数用于将请求路由到相应的 .
通常,您不会自己编写 router 函数,而是使用 Utility 类上的方法创建一个。 (无参数)为您提供用于创建路由器的 Fluent 构建器
函数,而提供直接的
创建路由器。HandlerFunctionRouterFunctionsRouterFunctions.route()RouterFunctions.route(RequestPredicate, HandlerFunction)
通常,建议使用构建器,因为它提供了
适用于典型映射场景的便捷捷径,无需难以发现
static imports。
例如,router 函数构建器提供了为 GET 请求创建 Map 的方法;和 POST。route()GET(String, HandlerFunction)POST(String, HandlerFunction)
除了基于 HTTP 方法的映射之外,路由构建器还提供了一种引入其他
谓词。
对于每个 HTTP 方法,都有一个重载的变体,它将 a 作为
参数,但可以表示其他约束。RequestPredicate
谓词
您可以编写自己的 ,但 utility 类
提供常用的实现,基于请求路径、HTTP 方法、内容类型、
等等。
以下示例使用请求谓词创建基于 header 的约束:RequestPredicateRequestPredicatesAccept
- 
Java
 - 
Kotlin
 
RouterFunction<ServerResponse> route = RouterFunctions.route()
	.GET("/hello-world", accept(MediaType.TEXT_PLAIN),
		request -> ServerResponse.ok().bodyValue("Hello World")).build();
val route = coRouter {
	GET("/hello-world", accept(TEXT_PLAIN)) {
		ServerResponse.ok().bodyValueAndAwait("Hello World")
	}
}
您可以使用以下方法将多个请求谓词组合在一起:
- 
RequestPredicate.and(RequestPredicate)— 两者必须匹配。 - 
RequestPredicate.or(RequestPredicate)— 两者都可以匹配。 
许多谓词都是组合的。
例如, 由 和 组成。
上面显示的示例还使用了两个请求谓词,因为生成器在内部使用,并使用谓词组合它。RequestPredicatesRequestPredicates.GET(String)RequestPredicates.method(HttpMethod)RequestPredicates.path(String)RequestPredicates.GETaccept
路线
路由器功能按顺序评估:如果第一个路由不匹配,则 second 被评估,依此类推。 因此,在一般路由之前声明更具体的路由是有意义的。 在将路由器函数注册为 Spring bean 时,这一点也很重要,也是如此 稍后描述。 请注意,此行为与基于 Comments 的编程模型不同,其中 “最具体”控制器方法会自动选取。
使用 router 函数构建器时,所有定义的路由都组合成一个路由,该路由从 返回。
还有其他方法可以将多个 router 功能组合在一起:RouterFunctionbuild()
- 
add(RouterFunction)在构建器上RouterFunctions.route() - 
RouterFunction.and(RouterFunction) - 
RouterFunction.andRoute(RequestPredicate, HandlerFunction)— 嵌套 的快捷方式 。RouterFunction.and()RouterFunctions.route() 
以下示例显示了四个路由的组合:
- 
Java
 - 
Kotlin
 
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
PersonRepository repository = ...
PersonHandler handler = new PersonHandler(repository);
RouterFunction<ServerResponse> otherRoute = ...
RouterFunction<ServerResponse> route = route()
	.GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) (1)
	.GET("/person", accept(APPLICATION_JSON), handler::listPeople) (2)
	.POST("/person", handler::createPerson) (3)
	.add(otherRoute) (4)
	.build();
| 1 | GET /person/{id}将匹配 JSON 的标头路由到AcceptPersonHandler.getPerson | 
| 2 | GET /person将匹配 JSON 的标头路由到AcceptPersonHandler.listPeople | 
| 3 | POST /person在没有其他谓词的情况下映射到 ,并且PersonHandler.createPerson | 
| 4 | otherRoute是在其他地方创建并添加到 Route built 的 router 函数。 | 
import org.springframework.http.MediaType.APPLICATION_JSON
val repository: PersonRepository = ...
val handler = PersonHandler(repository);
val otherRoute: RouterFunction<ServerResponse> = coRouter {  }
val route = coRouter {
	GET("/person/{id}", accept(APPLICATION_JSON), handler::getPerson) (1)
	GET("/person", accept(APPLICATION_JSON), handler::listPeople) (2)
	POST("/person", handler::createPerson) (3)
}.and(otherRoute) (4)
| 1 | GET /person/{id}将匹配 JSON 的标头路由到AcceptPersonHandler.getPerson | 
| 2 | GET /person将匹配 JSON 的标头路由到AcceptPersonHandler.listPeople | 
| 3 | POST /person在没有其他谓词的情况下映射到 ,并且PersonHandler.createPerson | 
| 4 | otherRoute是在其他地方创建并添加到 Route built 的 router 函数。 | 
嵌套路由
一组 router 函数通常具有共享谓词,例如
共享路径。在上面的示例中,共享谓词将是一个路径谓词,该
matches ,由三个路由使用。使用注释时,您需要删除
此复制通过使用映射到 .在 WebFlux.fn 中,路径谓词可以通过
router 函数构建器。例如,上面示例的最后几行可以是
通过使用嵌套路由,通过以下方式进行了改进:/person@RequestMapping/personpath
- 
Java
 - 
Kotlin
 
RouterFunction<ServerResponse> route = route()
	.path("/person", builder -> builder (1)
		.GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
		.GET(accept(APPLICATION_JSON), handler::listPeople)
		.POST(handler::createPerson))
	.build();
| 1 | 请注意,第二个参数 of 是采用路由器构建器的使用者。path | 
val route = coRouter { (1)
	"/person".nest {
		GET("/{id}", accept(APPLICATION_JSON), handler::getPerson)
		GET(accept(APPLICATION_JSON), handler::listPeople)
		POST(handler::createPerson)
	}
}
| 1 | 使用 Coroutines router DSL 创建 router;反应式替代方案也可通过以下方式获得。router { } | 
尽管基于路径的嵌套是最常见的,但你可以使用
构建器上的方法。
上面仍然包含一些共享 -header 谓词形式的重复。
我们可以通过将该方法与以下方法结合使用来进一步改进:nestAcceptnestaccept
- 
Java
 - 
Kotlin
 
RouterFunction<ServerResponse> route = route()
	.path("/person", b1 -> b1
		.nest(accept(APPLICATION_JSON), b2 -> b2
			.GET("/{id}", handler::getPerson)
			.GET(handler::listPeople))
		.POST(handler::createPerson))
	.build();
val route = coRouter {
	"/person".nest {
		accept(APPLICATION_JSON).nest {
			GET("/{id}", handler::getPerson)
			GET(handler::listPeople)
			POST(handler::createPerson)
		}
	}
}
| 1 | GET /person/{id}将匹配 JSON 的标头路由到AcceptPersonHandler.getPerson | 
| 2 | GET /person将匹配 JSON 的标头路由到AcceptPersonHandler.listPeople | 
| 3 | POST /person在没有其他谓词的情况下映射到 ,并且PersonHandler.createPerson | 
| 4 | otherRoute是在其他地方创建并添加到 Route built 的 router 函数。 | 
| 1 | GET /person/{id}将匹配 JSON 的标头路由到AcceptPersonHandler.getPerson | 
| 2 | GET /person将匹配 JSON 的标头路由到AcceptPersonHandler.listPeople | 
| 3 | POST /person在没有其他谓词的情况下映射到 ,并且PersonHandler.createPerson | 
| 4 | otherRoute是在其他地方创建并添加到 Route built 的 router 函数。 | 
| 1 | 请注意,第二个参数 of 是采用路由器构建器的使用者。path | 
| 1 | 使用 Coroutines router DSL 创建 router;反应式替代方案也可通过以下方式获得。router { } | 
服务资源
WebFlux.fn 提供对服务资源的内置支持。
除了下面描述的功能之外,由于 RouterFunctions#resource(java.util.function.Function)还可以实现更灵活的资源处理。 | 
重定向到资源
可以将与指定谓词匹配的请求重定向到资源。这可能很有用,例如, 用于处理单页应用程序中的重定向。
- 
Java
 - 
Kotlin
 
ClassPathResource index = new ClassPathResource("static/index.html");
List<String> extensions = Arrays.asList("js", "css", "ico", "png", "jpg", "gif");
RequestPredicate spaPredicate = path("/api/**").or(path("/error")).or(pathExtension(extensions::contains)).negate();
RouterFunction<ServerResponse> redirectToIndex = route()
	.resource(spaPredicate, index)
	.build();
val redirectToIndex = router {
	val index = ClassPathResource("static/index.html")
	val extensions = listOf("js", "css", "ico", "png", "jpg", "gif")
	val spaPredicate = !(path("/api/**") or path("/error") or
		pathExtension(extensions::contains))
	resource(spaPredicate, index)
}
从根位置提供资源
还可以将匹配给定模式的请求路由到相对于给定根位置的资源。
- 
Java
 - 
Kotlin
 
Resource location = new FileSystemResource("public-resources/");
RouterFunction<ServerResponse> resources = RouterFunctions.resources("/resources/**", location);
val location = FileSystemResource("public-resources/")
val resources = router { resources("/resources/**", location) }
除了下面描述的功能之外,由于 RouterFunctions#resource(java.util.function.Function)还可以实现更灵活的资源处理。 | 
运行 Server
如何在 HTTP 服务器中运行路由器功能?一个简单的选择是将路由器
函数设置为:HttpHandler
- 
RouterFunctions.toHttpHandler(RouterFunction) - 
RouterFunctions.toHttpHandler(RouterFunction, HandlerStrategies) 
然后,您可以按照 HttpHandler 获取特定于服务器的说明,将 return 与许多服务器适配器一起使用。HttpHandler
Spring Boot 也使用一个更典型的选项,是通过 WebFlux Config 使用基于DispatcherHandler的设置运行,它使用 Spring 配置来声明
处理请求所需的组件。WebFlux Java 配置声明以下内容
支持功能终端节点的基础设施组件:
- 
RouterFunctionMapping:在 Spring 中检测到一个或多个 bean 配置,对它们进行排序,通过 组合它们,并将请求路由到生成的 composed 。RouterFunction<?>RouterFunction.andOtherRouterFunction - 
HandlerFunctionAdapter:允许调用 a 映射到请求。DispatcherHandlerHandlerFunction - 
ServerResponseResultHandler:通过调用 .HandlerFunctionwriteToServerResponse 
前面的组件允许功能端点适应请求
处理生命周期,并且(可能)与带注释的控制器并行运行,如果
任何 (any) 都已声明。这也是 Spring Boot WebFlux 如何启用功能端点
起动机。DispatcherHandler
下面的示例显示了一个 WebFlux Java 配置(有关如何运行它,请参见DispatcherHandler):
- 
Java
 - 
Kotlin
 
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {
	@Bean
	public RouterFunction<?> routerFunctionA() {
		// ...
	}
	@Bean
	public RouterFunction<?> routerFunctionB() {
		// ...
	}
	// ...
	@Override
	public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
		// configure message conversion...
	}
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		// configure CORS...
	}
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
		// configure view resolution for HTML rendering...
	}
}
@Configuration
@EnableWebFlux
class WebConfig : WebFluxConfigurer {
	@Bean
	fun routerFunctionA(): RouterFunction<*> {
		// ...
	}
	@Bean
	fun routerFunctionB(): RouterFunction<*> {
		// ...
	}
	// ...
	override fun configureHttpMessageCodecs(configurer: ServerCodecConfigurer) {
		// configure message conversion...
	}
	override fun addCorsMappings(registry: CorsRegistry) {
		// configure CORS...
	}
	override fun configureViewResolvers(registry: ViewResolverRegistry) {
		// configure view resolution for HTML rendering...
	}
}
筛选处理程序函数
您可以通过在路由上使用 、 或 方法来筛选处理程序函数
函数构建器。
使用注释,您可以通过使用 、 a 或两者来实现类似的功能。
该筛选条件将应用于构建器构建的所有路由。
这意味着嵌套路由中定义的筛选条件不适用于 “top-level” 路由。
例如,请考虑以下示例:beforeafterfilter@ControllerAdviceServletFilter
- 
Java
 - 
Kotlin
 
RouterFunction<ServerResponse> route = route()
	.path("/person", b1 -> b1
		.nest(accept(APPLICATION_JSON), b2 -> b2
			.GET("/{id}", handler::getPerson)
			.GET(handler::listPeople)
			.before(request -> ServerRequest.from(request) (1)
				.header("X-RequestHeader", "Value")
				.build()))
		.POST(handler::createPerson))
	.after((request, response) -> logResponse(response)) (2)
	.build();
| 1 | 添加自定义请求标头的筛选条件仅适用于两个 GET 路由。before | 
| 2 | 记录响应的筛选条件将应用于所有路由,包括嵌套路由。after | 
val route = router {
	"/person".nest {
		GET("/{id}", handler::getPerson)
		GET("", handler::listPeople)
		before { (1)
			ServerRequest.from(it)
					.header("X-RequestHeader", "Value").build()
		}
		POST(handler::createPerson)
		after { _, response -> (2)
			logResponse(response)
		}
	}
}
| 1 | 添加自定义请求标头的筛选条件仅适用于两个 GET 路由。before | 
| 2 | 记录响应的筛选条件将应用于所有路由,包括嵌套路由。after | 
路由器构建器上的方法采用 : 一个
函数,该函数采用 AND 并返回 .
handler 函数参数表示链中的下一个元素。
这通常是路由到的处理程序,但也可以是另一个
filter (如果应用了多个)。filterHandlerFilterFunctionServerRequestHandlerFunctionServerResponse
现在我们可以向路由添加一个简单的安全过滤器,假设我们有一个
可以确定是否允许特定路径。
以下示例显示了如何执行此操作:SecurityManager
- 
Java
 - 
Kotlin
 
SecurityManager securityManager = ...
RouterFunction<ServerResponse> route = route()
	.path("/person", b1 -> b1
		.nest(accept(APPLICATION_JSON), b2 -> b2
			.GET("/{id}", handler::getPerson)
			.GET(handler::listPeople))
		.POST(handler::createPerson))
	.filter((request, next) -> {
		if (securityManager.allowAccessTo(request.path())) {
			return next.handle(request);
		}
		else {
			return ServerResponse.status(UNAUTHORIZED).build();
		}
	})
	.build();
val securityManager: SecurityManager = ...
val route = router {
		("/person" and accept(APPLICATION_JSON)).nest {
			GET("/{id}", handler::getPerson)
			GET("", handler::listPeople)
			POST(handler::createPerson)
			filter { request, next ->
				if (securityManager.allowAccessTo(request.path())) {
					next(request)
				}
				else {
					status(UNAUTHORIZED).build();
				}
			}
		}
	}
前面的示例演示了调用 is optional。
我们只允许在允许访问时运行处理程序函数。next.handle(ServerRequest)
除了在路由器函数构建器上使用该方法外,还可以应用
通过 Filter 筛选到现有路由器函数。filterRouterFunction.filter(HandlerFilterFunction)
对功能终端节点的 CORS 支持通过专用的 CorsWebFilter 提供。 | 
| 1 | 添加自定义请求标头的筛选条件仅适用于两个 GET 路由。before | 
| 2 | 记录响应的筛选条件将应用于所有路由,包括嵌套路由。after | 
| 1 | 添加自定义请求标头的筛选条件仅适用于两个 GET 路由。before | 
| 2 | 记录响应的筛选条件将应用于所有路由,包括嵌套路由。after | 
对功能终端节点的 CORS 支持通过专用的 CorsWebFilter 提供。 |