首页 > 其他分享 >Spring Cloud全解析:服务调用之Feign拦截器

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

时间:2024-09-23 10:12:31浏览次数:7  
标签:userName Feign 拦截器 Spring userId requestTemplate authentication

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()));
        }
    }
}

参考文献

标签:userName,Feign,拦截器,Spring,userId,requestTemplate,authentication
From: https://www.cnblogs.com/life-time/p/18426502

相关文章