Feign丢失请求头问题

【笔记于学习尚硅谷课程所作】

1、Feign远程调用丢失请求头问题

在这里插入图片描述

解决:增加拦截器

在这里插入图片描述

@Configuration
public class GuliFeignConfig {

    /**
     * 解决fein远程调用丢失请求头
     * @return
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                // 1、RequestContextHolder 拿到当前的请求
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if (attributes != null) {
                    // 原始请求 页面发起的老请求
                    HttpServletRequest request = attributes.getRequest();
                    if (request != null) {
                        // 获取原始请求的头数据 cookie
                        String cookie = request.getHeader("Cookie");

                        // 给feign生成的心请求设置请求头cookie
                        template.header("Cookie", cookie);
                    }
                }
            }
        };
    }
}

2、Feign异步调用丢失请求头问题

在这里插入图片描述

解决:获取之前的请求,让每个异步任务的线程共享ThreadLocal数据

/**
         * 解决异步任务拿不到ThreadLocal里的数据
         * 获取之前的请求,让每个异步任务的线程共享ThreadLocal数据
         */
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


CompletableFuture<Void> getAddressTask = CompletableFuture.runAsync(() -> {
			// 解决异步任务拿不到ThreadLocal里的数据
            RequestContextHolder.setRequestAttributes(requestAttributes); 

            //...
        }, executor);

猜你喜欢

转载自blog.csdn.net/qq_41596568/article/details/106593066