五分钟带你玩转springcloudNetflix(七)使用Feign调用时添加验证信息token到请求头

举报
小鲍侃java 发表于 2021/09/09 23:11:06 2021/09/09
【摘要】 1、这是最简单的一个方法,但是需要对每个调用都一一添加,就是使用@RequestHeader注解添加参数到请求头中去 @FeignClient(name = "capability-register", fallback = ApiServiceClientFallBack.class )public interface ApiSer...

1、这是最简单的一个方法,但是需要对每个调用都一一添加,就是使用@RequestHeader注解添加参数到请求头中去


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

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

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

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


  
  1. package com.hiynn.provider.configuration;
  2. import feign.RequestInterceptor;
  3. import feign.RequestTemplate;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.web.context.request.RequestContextHolder;
  6. import org.springframework.web.context.request.ServletRequestAttributes;
  7. import javax.servlet.http.HttpServletRequest;
  8. /**
  9. * @author lidai
  10. * @date 2019/2/27 16:14
  11. * <p>
  12. * Feign调用的时候添加请求头Token
  13. */
  14. @Configuration
  15. public class FeignConfiguration implements RequestInterceptor {
  16. @Override
  17. public void apply(RequestTemplate requestTemplate) {
  18. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  19. HttpServletRequest request = attributes.getRequest();
  20. requestTemplate.header("Token", request.getHeader("Token"));
  21. }
  22. }

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


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

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

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


  
  1. package com.hiynn.provider.configuration;
  2. import com.netflix.hystrix.HystrixThreadPoolKey;
  3. import com.netflix.hystrix.HystrixThreadPoolProperties;
  4. import com.netflix.hystrix.strategy.HystrixPlugins;
  5. import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;
  6. import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariable;
  7. import com.netflix.hystrix.strategy.concurrency.HystrixRequestVariableLifecycle;
  8. import com.netflix.hystrix.strategy.eventnotifier.HystrixEventNotifier;
  9. import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook;
  10. import com.netflix.hystrix.strategy.metrics.HystrixMetricsPublisher;
  11. import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy;
  12. import com.netflix.hystrix.strategy.properties.HystrixProperty;
  13. import lombok.extern.slf4j.Slf4j;
  14. import org.springframework.context.annotation.Configuration;
  15. import org.springframework.web.context.request.RequestAttributes;
  16. import org.springframework.web.context.request.RequestContextHolder;
  17. import java.util.concurrent.BlockingQueue;
  18. import java.util.concurrent.Callable;
  19. import java.util.concurrent.ThreadPoolExecutor;
  20. import java.util.concurrent.TimeUnit;
  21. /**
  22. * @author lidai
  23. * @date 2019/3/18 10:09
  24. */
  25. @Slf4j
  26. @Configuration
  27. public class FeignHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
  28. private HystrixConcurrencyStrategy delegate;
  29. public FeignHystrixConcurrencyStrategy() {
  30. try {
  31. this.delegate = HystrixPlugins.getInstance().getConcurrencyStrategy();
  32. if (this.delegate instanceof FeignHystrixConcurrencyStrategy) {
  33. // Welcome to singleton hell...
  34. return;
  35. }
  36. HystrixCommandExecutionHook commandExecutionHook =
  37. HystrixPlugins.getInstance().getCommandExecutionHook();
  38. HystrixEventNotifier eventNotifier = HystrixPlugins.getInstance().getEventNotifier();
  39. HystrixMetricsPublisher metricsPublisher = HystrixPlugins.getInstance().getMetricsPublisher();
  40. HystrixPropertiesStrategy propertiesStrategy =
  41. HystrixPlugins.getInstance().getPropertiesStrategy();
  42. this.logCurrentStateOfHystrixPlugins(eventNotifier, metricsPublisher, propertiesStrategy);
  43. HystrixPlugins.reset();
  44. HystrixPlugins.getInstance().registerConcurrencyStrategy(this);
  45. HystrixPlugins.getInstance().registerCommandExecutionHook(commandExecutionHook);
  46. HystrixPlugins.getInstance().registerEventNotifier(eventNotifier);
  47. HystrixPlugins.getInstance().registerMetricsPublisher(metricsPublisher);
  48. HystrixPlugins.getInstance().registerPropertiesStrategy(propertiesStrategy);
  49. } catch (Exception e) {
  50. log.error("Failed to register Sleuth Hystrix Concurrency Strategy", e);
  51. }
  52. }
  53. private void logCurrentStateOfHystrixPlugins(HystrixEventNotifier eventNotifier,
  54. HystrixMetricsPublisher metricsPublisher, HystrixPropertiesStrategy propertiesStrategy) {
  55. if (log.isDebugEnabled()) {
  56. log.debug("Current Hystrix plugins configuration is [" + "concurrencyStrategy ["
  57. + this.delegate + "]," + "eventNotifier [" + eventNotifier + "]," + "metricPublisher ["
  58. + metricsPublisher + "]," + "propertiesStrategy [" + propertiesStrategy + "]," + "]");
  59. log.debug("Registering Sleuth Hystrix Concurrency Strategy.");
  60. }
  61. }
  62. @Override
  63. public <T> Callable<T> wrapCallable(Callable<T> callable) {
  64. RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
  65. return new WrappedCallable<>(callable, requestAttributes);
  66. }
  67. @Override
  68. public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
  69. HystrixProperty<Integer> corePoolSize, HystrixProperty<Integer> maximumPoolSize,
  70. HystrixProperty<Integer> keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
  71. return this.delegate.getThreadPool(threadPoolKey, corePoolSize, maximumPoolSize, keepAliveTime,
  72. unit, workQueue);
  73. }
  74. @Override
  75. public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
  76. HystrixThreadPoolProperties threadPoolProperties) {
  77. return this.delegate.getThreadPool(threadPoolKey, threadPoolProperties);
  78. }
  79. @Override
  80. public BlockingQueue<Runnable> getBlockingQueue(int maxQueueSize) {
  81. return this.delegate.getBlockingQueue(maxQueueSize);
  82. }
  83. @Override
  84. public <T> HystrixRequestVariable<T> getRequestVariable(HystrixRequestVariableLifecycle<T> rv) {
  85. return this.delegate.getRequestVariable(rv);
  86. }
  87. static class WrappedCallable<T> implements Callable<T> {
  88. private final Callable<T> target;
  89. private final RequestAttributes requestAttributes;
  90. public WrappedCallable(Callable<T> target, RequestAttributes requestAttributes) {
  91. this.target = target;
  92. this.requestAttributes = requestAttributes;
  93. }
  94. @Override
  95. public T call() throws Exception {
  96. try {
  97. RequestContextHolder.setRequestAttributes(requestAttributes);
  98. return target.call();
  99. } finally {
  100. RequestContextHolder.resetRequestAttributes();
  101. }
  102. }
  103. }
  104. }

 

文章来源: baocl.blog.csdn.net,作者:小黄鸡1992,版权归原作者所有,如需转载,请联系作者。

原文链接:baocl.blog.csdn.net/article/details/107996832

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。