SpringCloud Feign转发请求头(防止session失效)的解决方案
微服务开发中经常有这样的需求,公司自定义了通用的请求头,需要在微服务的调用链中转发,比如在请求头中加入了token,或者某个自定义的信息uniqueid,总之就是自定义的一个键值对的东东,a服务调用b服务,b服务调用c服务,这样通用的东西如何让他在一个调用链中不断地传递下去呢?以a服务为例:
方案1
最傻的办法,在程序中获取,调用b的时候再转发,怎么获取在controller中国通过注解获取,或者通过request对象获取,这个不难,在请求b服务的时候,通过注解将值放进去即可;简代码如下:
获取: @requestmapping(value = "/api/test", method = requestmethod.get) public string testfun(@requestparam string name, @requestheader("uniqueid") string uniqueid) { if(uniqueid == null ){ return "must defined the uniqueid , it can not be null"; } log.info(uniqueid, "begin testfun... "); return uniqueid; }
然后a使用feign调用b服务的时候,传过去:
@feignclient(value = "demo-service") public interface callclient { /** * 访问demo-service服务的/api/test接口,通过注解将logid传递给下游服务 */ @requestmapping(value = "/api/test", method = requestmethod.get) string callapitest(@requestparam(value = "name") string name, @requestheader(value = "uniqueid") string uniqueid); }
方案弊端:毫无疑问,这方案不好,因为对代码有侵入,需要开发人员没次手动的获取和添加,因此舍弃
方案2
服务通过请求拦截器,在请求从a发送到b之后,在拦截器内将自己需要的东东加到请求头:
import com.intellif.log.loggerutili; import feign.requestinterceptor; import org.springframework.context.annotation.bean; 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; import java.util.enumeration; /** * 自定义的请求头处理类,处理服务发送时的请求头; * 将服务接收到的请求头中的uniqueid和token字段取出来,并设置到新的请求头里面去转发给下游服务 * 比如a服务收到一个请求,请求头里面包含uniqueid和token字段,a处理时会使用feign客户端调用b服务 * 那么uniqueid和token这两个字段就会添加到请求头中一并发给b服务; * * @author mozping * @version 1.0 * @date 2018/6/27 14:13 * @see feignheadconfiguration * @since jdk1.8 */ @configuration public class feignheadconfiguration { private final loggerutili logger = loggerutili.getlogger(this.getclass().getname()); @bean public requestinterceptor requestinterceptor() { return requesttemplate -> { servletrequestattributes attrs = (servletrequestattributes) requestcontextholder.getrequestattributes(); if (attrs != null) { httpservletrequest request = attrs.getrequest(); enumeration<string> headernames = request.getheadernames(); if (headernames != null) { while (headernames.hasmoreelements()) { string name = headernames.nextelement(); string value = request.getheader(name); /** * 遍历请求头里面的属性字段,将logid和token添加到新的请求头中转发到下游服务 * */ if ("uniqueid".equalsignorecase(name) || "token".equalsignorecase(name)) { logger.debug("添加自定义请求头key:" + name + ",value:" + value); requesttemplate.header(name, value); } else { logger.debug("feignheadconfiguration", "非自定义请求头key:" + name + ",value:" + value + "不需要添加!"); } } } else { logger.warn("feignheadconfiguration", "获取请求头失败!"); } } }; } }
网上很多关于这种方法的博文或者资料,大同小异,但是有一个问题,在开启熔断器之后,这里的attrs就是null,因为熔断器默认的隔离策略是thread,也就是线程隔离,实际上接收到的对象和这个在发送给b不是一个线程,怎么办?有一个办法,修改隔离策略hystrix.command.default.execution.isolation.strategy=semaphore,改为信号量的隔离模式,但是不推荐,因为thread是默认的,而且要命的是信号量模式,熔断器不生效,比如设置了熔断时间hystrix.command.default.execution.isolation.semaphore.timeoutinmilliseconds=5000,五秒,如果b服务里面sleep了10秒,非得等到b执行完毕再返回,因此这个方案也不可取;但是有什么办法可以在默认的thread模式下让拦截器拿到上游服务的请求头?自定义策略:代码如下:
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 org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.stereotype.component; 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; /** * 自定义feign的隔离策略; * 在转发feign的请求头的时候,如果开启了hystrix,hystrix的默认隔离策略是thread(线程隔离策略),因此转发拦截器内是无法获取到请求的请求头信息的,可以修改默认隔离策略为信号量模式:hystrix.command.default.execution.isolation.strategy=semaphore,这样的话转发线程和请求线程实际上是一个线程,这并不是最好的解决方法,信号量模式也不是官方最为推荐的隔离策略;另一个解决方法就是自定义hystrix的隔离策略,思路是将现有的并发策略作为新并发策略的成员变量,在新并发策略中,返回现有并发策略的线程池、queue;将策略加到spring容器即可; * * @author mozping * @version 1.0 * @date 2018/7/5 9:08 * @see feignhystrixconcurrencystrategyintellif * @since jdk1.8 */ @component public class feignhystrixconcurrencystrategyintellif extends hystrixconcurrencystrategy { private static final logger log = loggerfactory.getlogger(feignhystrixconcurrencystrategyintellif.class); private hystrixconcurrencystrategy delegate; public feignhystrixconcurrencystrategyintellif() { try { this.delegate = hystrixplugins.getinstance().getconcurrencystrategy(); if (this.delegate instanceof feignhystrixconcurrencystrategyintellif) { // 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(); } } } }
然后使用默认的熔断器隔离策略,也可以在拦截器内获取到上游服务的请求头信息了;
这里参考的博客,感谢这位大牛:https://blog.csdn.net/crystalqy/article/details/79083857
到此这篇关于springcloud feign转发请求头(防止session失效)的解决方案的文章就介绍到这了,更多相关springcloud feign转发请求头内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 如何构建一个Vue插件并生成npm包