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

本文介绍了在使用Feign进行服务调用时如何将验证信息token添加到请求头中的三种方法:1)通过@RequestHeader注解逐个添加;2)全局设置请求头;3)自定义并发策略实现自动添加Token。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

@FeignClient(name = “capability-register”, fallback = ApiServiceClientFallBack.class )
public interface ApiServiceClient {

@GetMapping("/api/fegin")
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);

}
其他几个参数都是调用fegin接口需要的参数,使用此接口时,直接获取验证信息放进token中,就可以了
2、这个方法是网上大多数人的用法,对所有的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

  • 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 Callable wrapCallable(Callable callable) {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    return new WrappedCallable<>(callable, requestAttributes);
    }

    @Override
    public ThreadPoolExecutor getThreadPool(HystrixThreadPoolKey threadPoolKey,
    HystrixProperty corePoolSize, HystrixProperty maximumPoolSize,
    HystrixProperty keepAliveTime, TimeUnit unit, BlockingQueue 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 getBlockingQueue(int maxQueueSize) {
    return this.delegate.getBlockingQueue(maxQueueSize);
    }

    @Override
    public HystrixRequestVariable getRequestVariable(HystrixRequestVariableLifecycle rv) {
    return this.delegate.getRequestVariable(rv);
    }

    static class WrappedCallable implements Callable {
    private final Callable 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();
         }
     }
    

    }
    }
    参考博客:https://blog.youkuaiyun.com/crystalqy/article/details/79083857

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值