feign获取响应头信息,feign 添加请求头
目录
假装调用添加验证信息代币到请求头1、这是最简单的一个方法2、这个方法是网上大多数人的用法3、第三种方法就是大神的方法了假装中增加请求头最近遇到项目在调用
Feign调用添加验证信息token到请求头
1、这是最简单的一个方法
但是需要对每个调用都一一添加,就是使用@请求标题注解添加参数到请求头中去
@ FeignClient(name= capability-register ,fallback=apiserviceclientfallback。类)公共接口API service client { @ get mapping(/API debug/)结果调试(@RequestParam(param )字符串路径,@RequestParam(method )字符串方法,@RequestParam(appKey )字符串appKey,@RequestHeader(name=Token ,required=true)字符串令牌);}这里需要注意,其他几个参数都是调用调试接口需要的参数,使用此接口时,直接获取验证信息放进代币中,就可以了
2、这个方法是网上大多数人的用法
但是我看到一个大神的博客,说是这种方法有点不好,然后大神自定义了一个高起鳞癣的策略,这个第三种方法再讲
这种方法是对所有的假装调用统一设置请求头
包com。你好。提供商。配置;导入佯请求拦截器导入佯。请求模板;导入org。spring框架。语境。注释。配置;导入组织。spring框架。网络。语境。请求。requestcontextholder导入组织。spring框架。网络。语境。请求。servletrequestattributes导入javax。servlet。http。http servlet请求;/* * * * @作者戴笠* @日期2019/2/27 16:14* p* Feign调用的时候添加请求头令牌*/@配置公共类FeignConfiguration实现请求拦截器{ @ Override public void apply(request template request template){ ServletRequestAttributes attributes=(ServletRequestAttributes)requestcontextholder。getrequestattributes();http servlet请求请求=属性。get request();requestTemplate.header(Token ,请求。get头( Token );}}有了配置之后还需要再假装添加配置属性
@ FeignClient(name= capability-register ,fallback=apiserviceclientfallback。class,configuration=feignconfiguration。类)公共接口API service client { @ get mapping(/API debug/)结果调试(@RequestParam(url )字符串路径,@RequestParam(param )字符串参数,@RequestParam(method )字符串方法,@RequestParam(a
ppKey") 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@Configurationpublic 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); }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持盛行IT。
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。