在spring Boot 3中有一个相当于feign的接口,Webclient或http接口的RequestInterceptor?

qq24tv8q  于 2023-04-30  发布在  Spring
关注(0)|答案(1)|浏览(317)

实际上,您可以如下实现RequestInterceptor

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.UUID;

public class TokenClientInterceptor implements RequestInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger(TokenClientInterceptor.class);

    public static final String TOKEN_HEADER_NAME = "my-token";

    @Override
    public void apply(RequestTemplate template) {
        var traceToken = computeTraceTokenIfAbsent();
        template.header(TOKEN_HEADER_NAME, traceToken);
    }

    private String computeTraceTokenIfAbsent() {
        try {
            var attribute =
                    RequestContextHolder.currentRequestAttributes()
                            .getAttribute(TOKEN_HEADER_NAME, RequestAttributes.SCOPE_REQUEST);
            if (attribute instanceof String strAttribute) {
                RequestContextHolder.currentRequestAttributes()
                        .setAttribute(TOKEN_HEADER_NAME, strAttribute, RequestAttributes.SCOPE_REQUEST);
                return strAttribute;
            }
        } catch (IllegalStateException e) {
            LOG.debug("Not in a request context: Creating new token for outgoing request.", e);
        }

        return UUID.randomUUID().toString();
    }
}

在spring Boot 3中有一个相当于feign的接口。Webclient或http接口的RequestInterceptor?
我找了几个小时,但没有结果。

xuo3flqw

xuo3flqw1#

据我所知,没有拦截机制。然而,他们确实提供了一个替代(在我看来更好)的策略来解决你的问题,即以一种新鲜的方式为每个请求添加一个头。

@Bean(“tokenedWebClient”)
public WebClient webClient() {
    return WebClient.builder()
    .baseUrl(someConfiguration.getApiUrl())
    .clientConnector(buildTimeoutConnector())
    .defaultHeaders(new Consumer<HttpHeaders>() {
      @Override
      public void accept(HttpHeaders httpHeaders) {
        httpHeaders.addAll(createHeaders());
      }
    })
    .build();
}

private HttpHeaders createHeaders() {
    HttpHeaders headers = new HttpHeaders();
    String traceToken = computeTraceTokenIfAbsent();
    headers.add(TOKEN_HEADER_NAME, traceToken);
    return headers;
}

相关问题