实际上,您可以如下实现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?
我找了几个小时,但没有结果。
1条答案
按热度按时间xuo3flqw1#
据我所知,没有拦截机制。然而,他们确实提供了一个替代(在我看来更好)的策略来解决你的问题,即以一种新鲜的方式为每个请求添加一个头。