WebFilter中的异步执行

时间:2018-10-04 12:46:21

标签: spring-webflux reactor

如何调用返回Mono <>的方法,并使用它来调用Web方法本身?

@Component
class SampleWebFilter(private val sampleService: SampleService) : WebFilter {
     override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
        val accessToken =
            exchange.request.headers["Authorization"]?.firstOrNull()
                    ?: throw IllegalArgumentException("Access token must not be empty")

        val res = sampleService.authorize(accessToken)

        val id = res.block()?.userId

        exchange.attributes["UserId"] = userId
        return chain.filter(exchange)
    }
}

@Component
interface SampleService {
    @GET("/user")
    fun authorize(accessToken): Mono<User>
}

上面的代码抛出异常 block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2

我知道我们不应该阻止netty上的线程,但是如何使用SampleService中的id来调用Web方法。

谢谢。

1 个答案:

答案 0 :(得分:1)

@Component
class SampleWebFilter(private val sampleService: SampleService) : WebFilter {
 override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
    val accessToken =
        exchange.request.headers["Authorization"]?.firstOrNull()
                ?: throw IllegalArgumentException("Access token must not be empty")

    val res = sampleService.authorize(accessToken)

    return res.doOnNext {
        exchange.attributes["UserId"] = userId
    }
    .then(chain.filter(exchange))
}}

@Component
interface SampleService {
    @GET("/user")
    fun authorize(accessToken): Mono<User>
}

我解决了如上所述的书写问题。