6

我有两种 Webflux 应用程序,基于注释的和基于路由的。这些应用程序使用一组标头调用,其中一些(开放跟踪)我需要在下游调用中使用WebClient.

如果这些是普通的 Spring WebMvc 应用程序,我将使用过滤器将选定的标头保留在 aThreadLocal中,在拦截器中访问它RestTemplate以将它们发送到后续服务并清除ThreadLocal.

在 WebFlux 应用程序中复制这种行为的正确方法是什么?

4

1 回答 1

11

我使用 Project Reactor 的 Context 将标题存储在 WebFilter 中解决了它。然后他们在 WebClient 的 ExchangeFilterFunction 中获取。这是整个解决方案:

网络过滤器

class OpenTracingFilter(private val openTracingHeaders: Set<String>) : WebFilter {

    private val logger = LoggerFactory.getLogger(javaClass)

    override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {

        return chain.filter(exchange)
                .subscriberContext { ctx ->
                    var updatedContext = ctx
                    exchange.request.headers.forEach {
                        if (openTracingHeaders.contains(it.key.toLowerCase())) {
                            logger.debug("Found OpenTracing Header - key {} - value {}", it.key, it.value[0])
                            updatedContext = updatedContext.put(it.key, it.value[0])
                        }
                    }
                    updatedContext
                }
    }
}

OpenTracingExchangeFilterFunction

class OpenTracingExchangeFilterFunction(private val headers: Set<String>) : ExchangeFilterFunction {

    private val logger = LoggerFactory.getLogger(javaClass)

    override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> {

        logger.debug("OpenTracingExchangeFilterFunction - filter()")
        return OpenTracingClientResponseMono(request, next, headers)
    }
}

OpenTracingClientResponseMono

class OpenTracingClientResponseMono(private val request: ClientRequest,
                                    private val next: ExchangeFunction,
                                    private val headersToPropagate: Set<String>) : Mono<ClientResponse>() {

    private val logger = LoggerFactory.getLogger(javaClass)

    override fun subscribe(subscriber: CoreSubscriber<in ClientResponse>) {
        val context = subscriber.currentContext()

        val requestBuilder = ClientRequest.from(request)
        requestBuilder.headers { httpHeaders ->
            headersToPropagate.forEach {
                if(context.hasKey(it)) {
                    logger.debug("Propagating header key {} - value{}", it, context.get<String>(it))
                    httpHeaders[it] = context.get<String>(it)
                }
            }
        }
        val mutatedRequest = requestBuilder.build()
        next.exchange(mutatedRequest).subscribe(subscriber)
    }


}

开放跟踪配置

@Configuration
class OpenTracingConfiguration(private val openTracingConfigurationProperties: OpenTracingConfigurationProperties) {

    @Bean
    fun webClient(): WebClient {
        return WebClient.builder().filter(openTracingExchangeFilterFunction()).build()
    }

    @Bean
    fun openTracingFilter(): WebFilter {
        return OpenTracingFilter(openTracingConfigurationProperties.headers)
    }

    @Bean
    fun openTracingExchangeFilterFunction(): OpenTracingExchangeFilterFunction {
        return OpenTracingExchangeFilterFunction(openTracingConfigurationProperties.headers)
    }
}

OpenTracingConfigurationProperties

@Configuration
@ConfigurationProperties("opentracing")
class OpenTracingConfigurationProperties {

    lateinit var headers: Set<String>

}

应用程序.yml

opentracing:
  headers:
    - x-request-id
    - x-b3-traceid
    - x-b3-spanid
    - x-b3-parentspanid
    - x-b3-sampled
    - x-b3-flags
    - x-ot-span-context
于 2019-04-10T14:54:21.163 回答