How to read the request id from http request header and delegate it to (all) http clients in a spring boot app

259 views Asked by At
  1. Reading of the incoming HTTP Requests with the request id is done by a jakarta.servlet.Filter.
@Component
class MdcFilter : Filter {
    private val log = KotlinLogging.logger {}

    override fun doFilter(request: ServletRequest?, response: ServletResponse?, chain: FilterChain?) {
        val httpRequest = request as HttpServletRequest
        val xRequestIdFromHeader = httpRequest.getHeader("X-Request-ID") ?: return
        MDC.put("X-Request-ID", xRequestIdFromHeader)
        log.debug { "X-Request-ID: $xRequestIdFromHeader is set as MDC variable" }
        chain?.doFilter(request, response)
        MDC.remove("X-Request-ID")
    }
}
  1. Now i would like to set all outgoing http request with the same request id. For that i configured the my Http Clients with the component below.
@Component
class RestTemplateConfig {

    @Bean
    private fun restTemplate(): RestTemplateBuilder =
        RestTemplateBuilder()
            // traceability
            .defaultHeader("X-Request-ID", "Where do i get the request id")
}
0

There are 0 answers