美文网首页
Spring Cloud全解析:服务调用之Feign拦截器

Spring Cloud全解析:服务调用之Feign拦截器

作者: 墨线宝 | 来源:发表于2024-09-22 10:17 被阅读0次

    Feign拦截器

    通过实现RequestInterceptor接口来实现Feign的拦截器,实现apply方法

    public class FeignRequestInterceptor implements RequestInterceptor
    {
        @Override
        public void apply(RequestTemplate requestTemplate)
        {
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    
            if (StringUtils.isNotNull(httpServletRequest))
            {
                Map<String, String> headers = ServletUtils.getHeaders(httpServletRequest);
                // 传递用户信息请求头,防止丢失
                String userId = headers.get("userId");
                if (StringUtils.isNotEmpty(userId))
                {
                    requestTemplate.header("userId", userId);
                }
                String userName = headers.get("userName");
                if (StringUtils.isNotEmpty(userName))
                {
                    requestTemplate.header("userName", userName);
                }
                String authentication = headers.get("authentication");
                if (StringUtils.isNotEmpty(authentication))
                {
                    requestTemplate.header("authentication", authentication);
                }
    
                // 配置客户端IP
                requestTemplate.header("X-Forwarded-For", IpUtils.getIpAddr(ServletUtils.getRequest()));
            }
        }
    }
    

    参考文献

    相关文章

      网友评论

          本文标题:Spring Cloud全解析:服务调用之Feign拦截器

          本文链接:https://www.haomeiwen.com/subject/dnbtrjtx.html