Feign客户端的拦截器

发布时间 2023-06-26 19:45:07作者: Rover20230226
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
@Component
public class MyFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        log.info("===request: {}", template.url());
        template.header("aaaa", "bbbb");
    }
}

这段代码是一个Feign客户端的拦截器,用于在客户端发送请求时,往HTTP请求Header中添加一个自定义的字段和字段值。

具体来说,这个拦截器实现了FeignRequestInterceptor接口,并重写了其中的apply方法。apply方法的作用是在发送请求之前对请求进行一些处理,例如添加Header、修改URL等。

apply方法中,首先通过RequestContextHolder.getRequestAttributes()获取到当前请求的上下文信息,然后通过template.header方法添加一个自定义的Header字段。在这里,添加的Header字段的名称为"aaaa",值为"bbbb"

最后,通过log.info方法打印出当前请求的URL,以便于调试和追踪请求。