Feign远程调用丢失请求头

Feign远程调用丢失请求头

feign远程调用接口,会新创建request导致丢失请求头 

Feign远程调用丢失请求头_第1张图片

 解决方法需要获取原请求头并同步

Feign远程调用丢失请求头_第2张图片

 使用 feign 自带请求拦截器 RequestInterceptor,在该拦截器中同步请求头

package com.hdb.pingmoweb.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class FeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest();
                if(request !=null){
                    String cookie = request.getHeader("Cookie");
                    requestTemplate.header("Cookie",cookie);
                }
            }
        };
    }

}

Feign异步调用丢失上下文

解决方案:使用异步编排需要给线程重新设置上下文,通过使用RequestContextHolder,获取和设置上下文

由于RequestContextHolder 内部维护了ThreadLocal,不同线程ThreadLocal 获取数据不同

Feign远程调用丢失请求头_第3张图片

下面是异步编排和RequestContextHolder使用代码

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    @RequestMapping("/feign")
    public R feign(HttpServletRequest request) throws ExecutionException, InterruptedException {

        Map> map = new HashMap<>();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        
        CompletableFuture future1 = CompletableFuture.runAsync(() -> {
            System.out.println("线程:"+Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List list1 = couponFeignService.info2(1L);
            map.put("list1", list1);
        }, executor);

        CompletableFuture future2 =CompletableFuture.runAsync(()->{
            System.out.println("线程:"+Thread.currentThread().getId());
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List list2 = couponFeignService.info2(1L);
            map.put("list2",list2);
        },executor);

        CompletableFuture future = CompletableFuture.allOf(future1, future2);
        future.get();

        return R.ok();
    }

你可能感兴趣的:(微服务,java,spring)