Feign客户端的拦截器

复制代码
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,以便于调试和追踪请求。

posted @   青核桃啊  阅读(562)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示