Spring WebFlux : Filters和Interceptor实现

Spring WebFlux 是一个基于spring 5+的reactive web 框架,filters 的实现和以前的spring mvc不一样,基本没有(Servlet Filter, HandlerInterceptor)这些了,而是全新的weblux风格的过滤器,下面介绍几种实现方式:

方法一:WebFilter

函数式的router风格:https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-fn

基于注解的web端:https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-controller

WebFilter 的 Kotlin 实现:

@Bean
fun sampleWebFilter(): WebFilter {
    return WebFilter { e: ServerWebExchange, c: WebFilterChain ->
        val l: MutableList = e.getAttributeOrDefault(KEY, mutableListOf())
        l.add("From WebFilter")
        e.attributes.put(KEY, l) // 目前发现attributes不能放mono和flux的对象
        c.filter(e)
    }
}

方法二:HandlerFilterFunction

基于函数式的路由方式,RouterFunctions提供钩子实现


@Bean
fun route(): RouterFunction<*> = router {
   GET("/react/hello", { r ->
       ok().body(fromObject(
               Greeting("${r.attribute(KEY).orElse("[Fallback]: ")}: Hello")
       ))
   POST("/another/endpoint", TODO())
   PUT("/another/endpoint", TODO())
})
}

HandlerFilterFunction 拦截请求:

fun route(): RouterFunction<*> = router {
   GET("/react/hello", { r ->
       ok().body(fromObject(
               Greeting("${r.attribute(KEY).orElse("[Fallback]: ")}: Hello")
       ))
   })
   POST("/another/endpoint", TODO())
   PUT("/another/endpoint", TODO())
}.filter({ r: ServerRequest, n: HandlerFunction ->
   val greetings: MutableList = r.attribute(KEY)
           .map { v ->
               v as MutableList
           }.orElse(mutableListOf())
   greetings.add("From HandlerFilterFunction")
   r.attributes().put(KEY, greetings)
   n.handle(r)
})

github:https://github.com/xlj44400/sample-webflux-web-testing

你可能感兴趣的:(Spring WebFlux : Filters和Interceptor实现)