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

参考文献


bug生产者
20 声望0 粉丝