精华内容
下载资源
问答
  • feign请求头传递

    2020-10-16 16:43:44
    前言:在我们token进行鉴权操作时,使用feign进行请求转发会导致请求头的丢失,这个时候就需要进行请求头传递操作 步骤一:创建feign拦截器 @Component public class FeignRequestInterceptor implements ...
    前言:在我们token进行鉴权操作时,使用feign进行请求转发会导致请求头的丢失,这个时候就需要进行请求头的传递操作
    • 步骤一:创建feign拦截器

      • @Component
        public class FeignRequestInterceptor implements RequestInterceptor {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes();
                if (Objects.isNull(attributes)){
                    return;
                }
                HttpServletRequest request = attributes.getRequest();
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames != null) {
                    while (headerNames.hasMoreElements()) {
                        String name = headerNames.nextElement();
                        String values = request.getHeader(name);
                        requestTemplate.header(name, values);
                    }
                }
            }
        }
        
    • 步骤二:Hystrix透传ThreadLocal数据

      • @Component
        public class RequestAttributeHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
        
            public RequestAttributeHystrixConcurrencyStrategy() {
                try {
                    HystrixPlugins.reset();
                    HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        
            @Override
            public <T> Callable<T> wrapCallable(Callable<T> callable) {
                RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
                return  new Callable<T>() {
                    @Override
                    public T call() throws Exception {
                        RequestContextHolder.setRequestAttributes(requestAttributes);
                        return callable.call();
                    }
                };
            }
        
        }
        
    展开全文
  • Feign传递请求头信息

    万次阅读 2018-09-15 09:38:20
    在我之前的文章服务网关Spring Cloud Zuul中,将用户的登录id放在了请求传递给...但是我们可以通过通过实现RequestInterceptor接口,完成对所有的Feign请求,传递请求和请求参数。 1. 实现RequestIntercep...

    在我之前的文章服务网关Spring Cloud Zuul中,将用户的登录id放在了请求头中传递给内部服务。但是当内部服务之间存在feign调用时,那么请求头信息会在feign请求的时候传递吗?不会,请求的头信息和请求参数都不会进行传递。但是我们可以通过通过实现RequestInterceptor接口,完成对所有的Feign请求,传递请求头和请求参数。

    1. 实现RequestInterceptor接口

    import feign.RequestInterceptor;
    import feign.RequestTemplate;
    import org.springframework.web.context.request.RequestContextHolder;
    import org.springframework.web.context.request.ServletRequestAttributes;
    
    import javax.servlet.http.HttpServletRequest;
    import java.util.Enumeration;
    
    /**
     * Feign请求拦截器(设置请求头,传递登录信息)
     *
     * @author simon
     * @create 2018-09-07 9:51
     **/
    public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
      @Override
      public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
          while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String values = request.getHeader(name);
            requestTemplate.header(name, values);
          }
        }
      }
    }

    这里只设置了请求头,如果想传递请求参数,可以参考如下代码:

    public class FeignBasicAuthRequestInterceptor implements RequestInterceptor {
      @Override
      public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
          while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String values = request.getHeader(name);
            requestTemplate.header(name, values);
          }
        }
        Enumeration<String> bodyNames = request.getParameterNames();
          StringBuffer body =new StringBuffer();
          if (bodyNames != null) {
              while (bodyNames.hasMoreElements()) {
                String name = bodyNames.nextElement();
                String values = request.getParameter(name);
                body.append(name).append("=").append(values).append("&");
              }
          }
         if(body.length()!=0) {
            body.deleteCharAt(body.length()-1);
            template.body(body.toString());
            logger.info("feign interceptor body:{}",body.toString());
        }
      }
    }

    2. 注册配置

    package com.southgis.ibase.personalConfigure.config;
    
    import com.southgis.ibase.utils.FeignBasicAuthRequestInterceptor;
    import com.southgis.ibase.utils.FeignSpringFormEncoder;
    import feign.RequestInterceptor;
    import feign.codec.Encoder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * Feign配置注册(全局)
     *
     * @author simon
     * @create 2018-08-20 11:44
     **/
    @Configuration
    public class FeignSupportConfig {
      /**
       * feign请求拦截器
       *
       * @return
       */
      @Bean
      public RequestInterceptor requestInterceptor(){
        return new FeignBasicAuthRequestInterceptor();
      }
    }

    这个文件放在项目的扫描目录下,所有的feign调用都会使用此配置。如果只有某个feign调用则可以这样设置(但配置类不能在扫描目录下):

    @FeignClient(name = "organ",path = "/organ/OrganInfo",configuration = FeignSupportConfig.class)
    展开全文
  • feign 全局传递请求头参数

    千次阅读 2019-09-04 19:57:30
    参考文档:...1、feign拦截器 @Configuration public class FeignConfiguration implements RequestInterceptor { @Override public void apply(RequestTemplate...

    参考文档:https://blog.csdn.net/lidai352710967/article/details/88680173

    1、feign拦截器

    @Configuration
    public class FeignConfiguration implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        requestTemplate.header("Token", request.getHeader("Token"));
    }
    

    上述方式只对semophone策略有效,需要如下配置

    hystrix:
      command:
        default:
          execution:
            isolation:
              strategy: SEMAPHORE
    
    

    2、自定义熔断策略,配合RequestInterceptor 使用

    
    import com.netflix.hystrix.HystrixThreadPoolKey;
    import com.netflix.hystrix.HystrixThreadPoolProperties;
    import com.netflix.hystrix.strategy.HystrixPlugins;
    import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
    import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable;
    import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle;
    import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
    import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
    import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
    import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
    import com.netflix.hystrix.strategy.properties.HystrixProperty;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.context.request.RequestAttributes;
    import org.springframework.web.context.request.RequestContextHolder;
    
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ThreadPoolExecutor;
    import java.util.concurrent.TimeUnit;
    
    /**
     * @Author: luosai
     * @Date: 2019/9/4 17:37
     */
    @Slf4j
    @Configuration
    public class FeignHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
      private HystrixConcurrencyStrategy delegate;
    
      public FeignHystrixConcurrencyStrategy() {
        try {
          this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy();
          if (this.delegate instanceof FeignHystrixConcurrencyStrategy) {
            // Welcome to singleton hell...
            return;
          }
          HystrixCommandExecutionHook commandExecutionHook =
                  HystrixPlugins.getInstance().getCommandExecutionHook();
          HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
          HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();
          HystrixPropertiesStrategy propertiesStrategy =
                  HystrixPlugins.getInstance().getPropertiesStrategy();
          this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher, propertiesStrategy);
          HystrixPlugins.reset();
          HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
          HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
          HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
          HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
          HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
        } catch (Exception e) {
          log.error("Failed to register Sleuth Hystrix Concurrency Strategy", e);
        }
      }
    
      private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier,
                                                   HystrixMetricsPublisher metricsPublisher, HystrixPropertiesStrategy propertiesStrategy) {
        if (log.isDebugEnabled()) {
          log.debug("Current Hystrix plugins configuration is [" + "concurrencyStrategy ["
                  + this.delegate + "]," + "eventNotifier [" + eventNotifier + "]," + "metricPublisher ["
                  + metricsPublisher + "]," + "propertiesStrategy [" + propertiesStrategy + "]," + "]");
          log.debug("Registering Sleuth Hystrix Concurrency Strategy.");
        }
      }
    
      @Override
      public <T> Callable<T> wrapCallable(Callable<T> callable) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return new WrappedCallable<>(callable, requestAttributes);
      }
    
      @Override
      public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
                                              HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize,
                                              HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime,
                unit, workQueue);
      }
    
      @Override
      public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
                                              HystrixThreadPoolProperties threadPoolProperties) {
        return this.delegate.getThreadPool(threadPoolKey, threadPoolProperties);
      }
    
      @Override
      public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
        return this.delegate.getBlockingQueue(maxQueueSize);
      }
    
      @Override
      public <T> HystrixRequestVariable<T> getRequestVariable(HystrixRequestVariableLifecycle<T> rv) {
        return this.delegate.getRequestVariable(rv);
      }
    
      static class WrappedCallable<T> implements Callable<T> {
        private final Callable<T> target;
        private final RequestAttributes requestAttributes;
    
        public WrappedCallable(Callable<T> target, RequestAttributes requestAttributes) {
          this.target = target;
          this.requestAttributes = requestAttributes;
        }
    
        @Override
        public T call() throws Exception {
          try {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            return target.call();
          } finally {
            RequestContextHolder.resetRequestAttributes();
          }
        }
      }
    
    
    }
    
    
    展开全文
  • Spring Cloud Feign 请求时附带请求头

    千次阅读 2020-10-15 09:51:12
    Spring Cloud Feign 请求时附带请求头问题描述解决方案FeignConfiguration使用配置修改 问题描述 Feign请求时是不会将 request 的请求头带着请求的,导致假如 Feign 调用的接口需要请求头的信息,比如当前用户的 ...

    Spring Cloud Feign 请求时附带请求头

    问题描述

    Feign 在请求时是不会将 request 的请求头带着请求的,导致假如 Feign 调用的接口需要请求头的信息,比如当前用户的 token 之类的就获取不到

    解决方案

    FeignConfiguration

    通过实现 Feign 的 RequestInterceptor 将从上下文中获取到的请求头信息循环设置到 Feign 请求头中。

    /**
     * feign 配置文件
     * 将请求头中的参数,全部作为 feign 请求头参数传递
     * @author: linjinp
     * @create: 2020-06-28 09:54
     **/
    @Configuration
    public class FeignConfiguration implements RequestInterceptor {
        @Override
        public void apply(RequestTemplate requestTemplate) {
            HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    requestTemplate.header(name, values);
                }
            }
        }
    }
    

    使用

    通过 configuration = FeignConfiguration.class 指定这次 Feign 请求走哪种配置

    @FeignClient(name = "admin", contextId = "factoryPlmseriesRelation", configuration = FeignConfiguration.class)
    //@FeignClient(name = "admin2", contextId = "factoryPlmseriesRelation", url = "http://127.0.0.1:8582/", configuration = FeignConfiguration.class)
    public interface FeignFactoryPlmseriesRelationService {
    
        /**
         * 根据当前用户,获取工厂与PLM关联关系
         * @return
         */
        @GetMapping(value = "/factoryPlmseriesRelation/getFactoryPlmseriesRelation")
        ErrorMsg<List<FactoryPlmseriesRelationVo>> getFactoryPlmseriesRelation();
    
    }
    

    配置修改

    主要是 hystrix.command.default.execution.isolation 后面的配置,需要将 hystrix 配置为信号量模式,否则会出现由于隔离策略导致获取不到请求头

    # ribbon 配置
    ribbon:
      OkToRetryOnAllOperations: false #对所有操作请求都进行重试,默认false
      ReadTimeout: 5000   #负载均衡超时时间,默认值5000
      ConnectTimeout: 5000 #ribbon请求连接的超时时间,默认值2000
      MaxAutoRetries: 0     #对当前实例的重试次数,默认0
      MaxAutoRetriesNextServer: 1 #对切换实例的重试次数,默认1
    # hystrix 配置
    hystrix:
      command:
        default:  #default全局有效,service id指定应用有效
          execution:
            timeout:
              #是否开启超时熔断
              enabled: true
            isolation:
              thread:
                timeoutInMilliseconds: 10000 #断路器超时时间,默认1000ms
              # hystrix 隔离模式改为信号量模式,feign 才能获取到父线程中的请求头
              strategy: SEMAPHORE
              # 允许的并发量,默认值为 10
              semaphore:
                maxConcurrentRequests: 100
    
    展开全文
  • Feign 支持请求拦截器,在发送请求前,可以对发送的模板进行操作,例如设置请求头等属性,自定请求拦截器需要实现 feign.RequestInterceptor 接口,该接口的方法 apply 有参数 template ,该参数类型为 ...
  • SpringCloudFeign请求拦截器说明 周所周知,feign在调用微服务系统中的某一服务时是无法携带前端请求后台时所带来的请求信息的,例如token,这对于使用token验证的系统来说是很致命的;还有一种情况就是说当你使用...
  • 1.SpringCloud中微服务之间的调用,传递参数时需要加相应的注解。用到的主要是三个注解@RequestBody,@RequestParam(),@PathVariable() 2.get和post请求中对于传递单个引用类型的参数,比如String,Integer....用@...
  • @GetMapping(value = "/classes") Object getClasses(@SpringQueryMap ClassesQueryParam classesQueryParam); 添加springQueryMap 依赖 <dependency> <groupId>org.springframework.cloud<...
  • feign请求参数

    2020-02-11 02:33:42
    1.SpringCloud中微服务之间的调用,传递参数时需要加相应的注解。用到的主要是三个注解@RequestBody,@RequestParam(),@PathVariable() 2.get和post请求中对于传递单个引用类型的参数,比如String,Integer....用@...
  • 例如Token或者cookie信息,因为在调用远程接口时,会进行RequestInterceptor的遍历,但是默认容器中是没有的,所以请求信息和请求参数都不会进行传递。我们可以通过实现RequestInterceptor注入容器,将请求相关...
  • Feign GET方式传递多个参数
  • 解决方式:实现RequestInterceptor接口(对所有的Feign请求进行拦截,从request中取参数进行构造,主要代码:requestTemplate.header(name, values)) 代码: import feign.RequestInterce...
  • feignclient发送get请求传递参数为对象。此时不能使用在地址栏传递参数的方式,需要将参数放到请求体中。第一步:修改application.yml中配置feign发送请求使用apache httpclient 而不是默认的jdk ...
  • 本来用POJO类型作为request的请求体参数,测试feign请求转发,引入SpringFormEncoder后很快解决了 feign.codec.NullPointerException异常。 ​ 但是,实际上,别人想用我这个FeignClient就必须要知道 POJO类型格式...
  • Feign GET方式传递参数 单个参数 错误示例 @FeignClient(name = "demoFeignClient") public interface DemoFeignClient { @RequestMapping(value = "/test", method = RequestMethod.GET) ...
  • Feign-Feign参数请求

    2019-09-02 21:27:17
    一)单个参数传递 1.在服务项目内添加一个的参数的方法 注意使用Fegin进行参数传递的时候接口内的参数必须被@RequestParam注解指定参数的名称 /** * @param * @description: 使用参数传递的时候必须要使用@...
  • 首先需要写一个 Feign请求拦截器,通过实现RequestInterceptor接口,完成对所有的Feign请求,传递请求和请求参数。 Feign 请求拦截器 public class FeignBasicAuthRequestInterceptor implements RequestInterceptor...
  • 来源:https://blog.csdn.net/justlpf/article/details/86627642 版权声明:lpf ...参考文章: [SpringCloud-Feign] Feign转发请求头,(防止session失效) feign调用session丢失解决方案 目录...
  • 背景 微服务调用的时候请求不会...通过实现RequestInterceptor接口,完成对所有的Feign请求,传递请求和请求参数。本质是通过ThreadLocal线程共享变量实现. 代码实现 package com.kenai.gulimall.order.feign; i..
  • SpringCloud通过Feign传递List类型参数

    万次阅读 2019-10-14 19:59:15
    首先明确一点,SpringCloud通过Fegin如果是多个参数,其中一个参数是List,那么是传不过去的,单个List是可以的。 1、单个List实体传递 @RequestMapping("/secret/batchInsert") public int batchInsert(@Request...
  • spring cloud feign 调用微服务转发不了request请求参数...原理:为feign添加拦截,修改默认config,为feign请求添加原request的请求以及参数! 相关代码如下:代码块@Configuration public class FeignConfiguration
  • 声明式调用Feign请求参数

    千次阅读 2018-09-15 09:17:16
    1、Feign请求参数说明   Feign是Netflix的产品,Spring Cloud Feign是在原生Feign的基础上进行了封装。由于Spring Cloud Feign引入了许多springmvc的注解,方便springmvc的使用者使用,但同时也给使用者带来了很...
  • 1.通过feign 在通讯的过程,请求头需要传递,在feign 层做拦截,把当前的请求头信息放到下一次请求头中,如果当前线程中使用多线程调用服务,需要注意,子线程不结束,主线程不能结束,如果主线程结束,子线程子获取...
  • 叙述 spring cloud技术栈里面,Feign可以使得我们的rest调用和调用本地方法一样方便。但是它真的有非常多的坑,苦不堪言啊。...Feign发送Get请求时,采用POJO传递参数,报异常 Request metho...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 4,302
精华内容 1,720
关键字:

feign请求头传递参数