- Webflux是一个非阻塞的web框架。
- Webflux可以容纳都多的请求
它不会阻塞请求,当有更多的请求到达时,会将请求封装为事件,放在队列中等待执行。 - 数据可变
在Reactive pipeline中执行的所有的操作都是有顺序的,不会出现并发操作数据的情况,除非你手动创建了Thread去执行。 - 编码与解码
spring-core 模块提供了byte[],ByteBuffer,DataBuffer,Resource和String的解码与编码,spring-web模块提供了Jackson JSON,Jackson Smile,JAXB2,Protocol Buffers和其它的Http专用的解码和编码,比如form data,multipart content,server-sent events。
可以使用ClientCodecConfigurer和ServerCodecConfigurer配置自定义的解码编码器。更多可以查阅Http message codecs。 - Log Id
在webflux中,一个请求,有可能在多个线程中执行,所以线程id关联一个请求的日志信息也是没有什么用的,因此,WebFlux在收到请求时,会指定一个详细的请求ID,在服务器端,log id存储在ServerWebExchange
attribute (LOG_ID_ATTRIBUTE
),
在客户端,是存储在ClientRequest
attribute (LOG_ID_ATTRIBUTE
)可以通过ClientRequest#logPrefix().获取。 - 自定义解码器
客户端配置自定义解码器如下面代码所示:
Consumer<ClientCodecConfigurer> consumer = configurer -> {
CustomDecoder customDecoder = new CustomDecoder();
configurer.customCodecs().decoder(customDecoder);
configurer.customCodecs().withDefaultCodecConfig(config ->
customDecoder.maxInMemorySize(config.maxInMemorySize())
);
}
WebClient webClient = WebClient.builder()
.exchangeStrategies(strategies -> strategies.codecs(consumer))
.build();
自定义Controller中的条件注解
Spring WebFlux also supports custom request mapping attributes with custom request matching logic. This is a more advanced option that requires sub-classing RequestMappingHandlerMapping and overriding the getCustomMethodCondition method, where you can check the custom attribute and return your own RequestCondition.Java代码动态注册Handler Methods
@Configuration
public class MyConfig {
@Autowired
public void setHandlerMapping(RequestMappingHandlerMapping mapping, UserHandler handler)
throws NoSuchMethodException {
RequestMappingInfo info = RequestMappingInfo
.paths("/user/{id}").methods(RequestMethod.GET).build();
Method method = UserHandler.class.getMethod("getUser", Long.class);
mapping.registerMapping(info, handler, method);
}
}
1,Inject target handlers and the handler mapping for controllers.
2,Prepare the request mapping metadata.
3,Get the handler method.
4,Add the registration.
在Controller中可以直接返回HttpHeaders,表示只返回http header,没有body
Controller中参数类型转换
Some annotated controller method arguments that represent String-based request input (for example,@RequestParam
,@RequestHeader
,@PathVariable
,@MatrixVariable
, and@CookieValue
) can require type conversion if the argument is declared as something other thanString
.
For such cases, type conversion is automatically applied based on the configured converters. By default, simple types (such asint
,long
,Date
, and others) are supported. Type conversion can be customized through aWebDataBinder
(see [mvc-ann-initbinder]) or by registeringFormatters
with theFormattingConversionService
(see Spring Field Formatting).