diff --git a/spring/webflux/spring webflux.md b/spring/webflux/spring webflux.md index 1b9e3cd..2a099ee 100644 --- a/spring/webflux/spring webflux.md +++ b/spring/webflux/spring webflux.md @@ -274,5 +274,34 @@ Mono> getMultipartData(); 对于`WebFilter`的优先级,欸可以通过使用`@Order`注解或实现`Ordered`接口来实现。 -#### CORS -spring webflux支持通过@CORSLAI1 \ No newline at end of file +#### UrlHandler +在编写web程序时,可能希望controller endpoint既能够匹配末尾带`/`的url版本,又能匹配末尾不带`/`的url版本。 + +> 例如,想要让`@GetMapping("/home")`既能够匹配`GET /home`,又能够匹配`GET /home/`。 + +对此,可以使用`UrlHandlerFilter`进行处理,其支持如下两种配置: +- 当接收到带有末尾带有`/`的url时,向浏览器返回一个重定向状态,让浏览器重新请求末尾不带`/`的url +- 将请求当作不带末尾`/`,并对请求继续处理 + +实例化UrlHandlerFilter的示例如下: +```java +UrlHandlerFilter urlHandlerFilter = UrlHandlerFilter + // will HTTP 308 redirect "/blog/my-blog-post/" -> "/blog/my-blog-post" + .trailingSlashHandler("/blog/**").redirect(HttpStatus.PERMANENT_REDIRECT) + // will mutate the request to "/admin/user/account/" and make it as "/admin/user/account" + .trailingSlashHandler("/admin/**").mutateRequest() + .build(); +``` + +#### Exceptions +在`WebHandler Api`中,可以使用`WebExceptionHandler`对异常进行处理。当使用`Webflux Config`时,注册`WebExceptionHandler`仅需将其声明为bean即可,可以通过`@Order`注解或`Ordered`接口来指明顺序。 + +#### Logging +##### Log Id +在webflux中,同一个请求可能在多个线程中被执行过,故而,在定位请求日志时,无法通过线程id来关联请求。为了解决该问题,spring webflux在打印消息时前缀了一个`log id`,其是针对单个特定请求的。 + +在server端,log id存储在`ServerWebExchange`中的`LOG_ID_ATTRIBUTE`属性中。在client端,log id存储在`Client Request`中的`LOG_ID_ATTRIBUTE`属性中。 + +##### Appenders +`slf4j`和`log4j`等日志库都提供异步logger,用于避免阻塞。使用异步logger会存在部分缺点,例如`丢弃无法排队的异步消息`。但是,其仍然是目前非阻塞框架的最佳选择。 +