Feign 远程调用丢失请求头和异步调用丢失上下文、支持Multipart格式传参

文章目录

  • 远程调用丢失请求头
  • 异步调用丢失上下文
  • 支持Multipart格式传参

<dependency>
   <groupId>org.springframework.cloudgroupId>
   <artifactId>spring-cloud-starter-openfeignartifactId>
   <version>2.2.7.RELEASEversion>
dependency>

远程调用丢失请求头

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

import javax.servlet.http.HttpServletRequest;

/**
 * 调用方配置
 *
 * @author dc
 * @version 1.0
 * @date 2023/03/08 15:01
 */
@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 (); // 老请求
                // 同步新请求
                String cookie = request.getHeader ("Cookie");
                // 设置新请求的Cookie
                requestTemplate.header ("Cookie", cookie);
            }
        };
    }
}

异步调用丢失上下文



private static final ThreadPoolExecutor THREADPOOLEXECUTOR =
          new ThreadPoolExecutor (
                  100,
                  100,
                  100,
                  TimeUnit.SECONDS,
                  new ArrayBlockingQueue<> (1000));

  public static void main(String[] args) {
      RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes ();

      CompletableFuture<Void> task1 = CompletableFuture.runAsync (() -> {
          // 解决Feign异步调用丢失上下文的问题
          RequestContextHolder.setRequestAttributes (requestAttributes);

      }, THREADPOOLEXECUTOR);
      CompletableFuture<Void> task2 = CompletableFuture.runAsync (() -> {
          // 解决Feign异步调用丢失上下文的问题
          RequestContextHolder.setRequestAttributes (requestAttributes);

      }, THREADPOOLEXECUTOR);

      // 等待任务都完成
      try {
          CompletableFuture.allOf (task1, task2).get ();
      } catch (InterruptedException | ExecutionException e) {
          throw new RuntimeException (e);
      }

  }

支持Multipart格式传参


<dependency>
    <groupId>io.github.openfeign.formgroupId>
    <artifactId>feign-formartifactId>
    <version>3.8.0version>
dependency>

<dependency>
    <groupId>io.github.openfeign.formgroupId>
    <artifactId>feign-form-springartifactId>
    <version>3.8.0version>
dependency>

你可能感兴趣的:(SpringCloud,java,spring,开发语言)