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

2024-09-22  本文已影响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()));
        }
    }
}

参考文献

上一篇下一篇

猜你喜欢

热点阅读