使用Feign调用时添加验证信息token到请求头方式

 更新时间:2022年03月04日 15:54:55   作者:木子人弋山  
这篇文章主要介绍了使用Feign调用时添加验证信息token到请求头方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

Feign调用添加验证信息token到请求头

1、这是最简单的一个方法

但是需要对每个调用都一一添加,就是使用@RequestHeader注解添加参数到请求头中去

@FeignClient(name = "capability-register", fallback = ApiServiceClientFallBack.class )
public interface ApiServiceClient { 
    @GetMapping("/apiDebug/")
    Result debug(@RequestParam("url") String path,
                 @RequestParam("param") String param,
                 @RequestParam("method") String method,
                 @RequestParam("appKey") String appKey,
                 @RequestHeader(name = "Token",required = true) String Token);
}

这里需要注意,其他几个参数都是调用debug接口需要的参数,使用此接口时,直接获取验证信息放进token中,就可以了

2、这个方法是网上大多数人的用法

但是我看到一个大神的博客,说是这种方法有点不好,然后大神自定义了一个Hystrix的策略,这个第三种方法再讲

这种方法是对所有的feign调用统一设置请求头

package com.hiynn.provider.configuration; 
import feign.RequestInterceptor;
import feign.RequestTemplate;
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 lidai
 * @date 2019/2/27 16:14
 * <p>
 * Feign调用的时候添加请求头Token
 */
@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"));
    }
}

有了configuration之后还需要再feign添加configuration属性

@FeignClient(name = "capability-register", fallback = ApiServiceClientFallBack.class ,configuration = FeignConfiguration.class)
public interface ApiServiceClient {
 
    @GetMapping("/apiDebug/")
    Result debug(@RequestParam("url") String path,
                 @RequestParam("param") String param,
                 @RequestParam("method") String method,
                 @RequestParam("appKey") String appKey);
}

到这里的时候,如果你debug的话,会发现FeignConfiguration中的attributes获取不到,需要再配置文件中添加如下配置就可以了

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

3、第三种方法就是大神的方法了

和第二种方法的区别就是不需要添加配置文件,但是FeignConfiguration这个还是要的,不需要加配置文件就加一个自定义策略

package com.hiynn.provider.configuration; 
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 lidai
 * @date 2019/3/18 10:09
 */
@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();
            }
        }
    }  
}

加上这个就可以了,亲测三种方法均可行。 

Feign中增加请求头

最近遇到项目在调用

实现RequestInterceptor 接口,然后可以根据feignClient中的值加到请求头中,使用时候在feignClient中配置,这样就可以把参数传入feign中

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.collections4.CollectionUtils; 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
  
public class FeignConfiguration implements RequestInterceptor {  
    @Override
    public void apply(RequestTemplate template) {
 
        List<String> list = new ArrayList<>();
        if ("get".equalsIgnoreCase(template.method())){
            Map<String, Collection<String>> queries = template.queries();
            list = (List<String>) queries.get("key");
 
        } else if ("post".equalsIgnoreCase(template.method())){
            byte[] body = template.body();
            Map<String, Object> map = JSONObject.parseObject(body, Map.class);
            Object key = map.get("key");
            if (key != null){
                list.add(key.toString());
            }
        }
        if (CollectionUtils.isNotEmpty(list)) {
            template.header("head", list);
        }
    } 
}
import com.hbasesoft.vcc.sgp.integral.goods.config.FeignConfiguration;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam; 
 
@FeignClient(name = "test", path = "/test", configuration = FeignConfiguration.class)
public interface ErpGoodsCouponsExternalClient {
 
    @GetMapping("/url")
    Object getData(@RequestParam("key") String key);    
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • JavaWeb登陆功能实现代码

    JavaWeb登陆功能实现代码

    这篇文章主要为大家详细介绍了JavaWeb登陆功能实现代码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • Spring Boot整合Swagger2的完整步骤详解

    Spring Boot整合Swagger2的完整步骤详解

    这篇文章主要给大家介绍了关于Spring Boot整合Swagger2的完整步骤,文中通过示例代码将整合的步骤一步步介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-07-07
  • 深入解析MybatisPlus多表连接查询

    深入解析MybatisPlus多表连接查询

    在一些复杂的业务场景中,我们经常会遇到多表连接查询的需求,本文主要介绍了深入解析MybatisPlus多表连接查询,具有一定的参考价值,感兴趣的可以了解一下
    2024-06-06
  • 解决MyBatis报错:There is no getter for property named'Xxx'in'class xxx.xxx.Xxx'

    解决MyBatis报错:There is no getter for 

    这篇文章主要介绍了解决MyBatis报错:There is no getter for property named'Xxx'in'class xxx.xxx.Xxx'问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-08-08
  • 面试题:Java 实现查找旋转数组的最小数字

    面试题:Java 实现查找旋转数组的最小数字

    这篇文章主要介绍了Java 实现查找旋转数组的最小数字,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • Java秒杀系统:web层详解

    Java秒杀系统:web层详解

    本文主要介绍了如何设计一个秒杀系统的web层相关知识。具有很好的参考价值。下面跟着小编一起来看下吧,希望能够给你带来帮助
    2021-10-10
  • Java logback日志的简单使用

    Java logback日志的简单使用

    这篇文章主要介绍了Java logback日志的使用详解,帮助大家更好的理解和学习使用Java,感兴趣的朋友可以了解下
    2021-03-03
  • Java实现调用ElasticSearch API的示例详解

    Java实现调用ElasticSearch API的示例详解

    这篇文章主要为大家详细介绍了Java调用ElasticSearch API的效果资料,文中的示例代码讲解详细,具有一定的参考价值,感兴趣的可以了解一下
    2023-03-03
  • Maven工程打包jar的多种方式

    Maven工程打包jar的多种方式

    Maven打包一般可以生成两种包一种是可以直接运行的包,一种是依赖包(只是编译包),这篇文章主要介绍了Maven工程打包jar的多种方式步骤详解,需要的朋友可以参考下
    2023-04-04
  • java lambda 表达式中的双冒号的用法说明 ::

    java lambda 表达式中的双冒号的用法说明 ::

    这篇文章主要介绍了java lambda 表达式中的双冒号的用法说明 ::具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09

最新评论