java吧 关注:1,190,795贴子:12,602,715
  • 16回复贴,共1
老哥们问个feign相关的问题用springcloud里的feign。通过feign接口调用的服务,由于feign传递过程中header会丢失,因此通过了一个feignConfig将原请求中header的token传递过去了(到这里为止都没问题。)然后用hystrix里的fallback想结合feign实现服务降级,但是这里token怎么都传不过去请问大佬们怎么解决,听网上说是因为hystrix切换线程了?


IP属地:浙江来自Android客户端1楼2022-05-12 15:35回复
    顶,有大佬吗


    IP属地:浙江来自Android客户端2楼2022-05-12 16:03
    回复
      mark一下,容我电脑端上代码


      IP属地:四川来自Android客户端3楼2022-05-12 16:28
      回复


        来自Android客户端4楼2022-05-12 16:28
        回复
          增加消息绑定类
          import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;import org.springframework.web.context.request.RequestAttributes;import org.springframework.web.context.request.RequestContextHolder;import java.util.concurrent.Callable;/** * 此类能够保证:RequestContext请求上下文,也就是RequestAttributes能够在线程池里自动有效 */public class RequestContextHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy { // 这个时候还在主线程了,所以通过RequestContextHolder.getRequestAttributes()是能拿到上下文的 // 拿到后hold住,等到run执行的时候再绑定即可 @override public <T> Callable<T> wrapCallable(Callable<T> callable) { return new RequestAttributeAwareCallable<>(callable, RequestContextHolder.getRequestAttributes()); } static class RequestAttributeAwareCallable<T> implements Callable<T> { private final Callable<T> delegate; private final RequestAttributes requestAttributes; public RequestAttributeAwareCallable(Callable<T> callable, RequestAttributes requestAttributes) { this.delegate = callable; this.requestAttributes = requestAttributes; } // 执行之前绑定上下文,执行完成后释放 @Override public T call() throws Exception { try { RequestContextHolder.setRequestAttributes(requestAttributes); return delegate.call(); } finally { RequestContextHolder.resetRequestAttributes(); } } }}
          在fegin的配置类中初始化插件类
          @PostConstructpublic void plugin(){ HystrixPlugins.getInstance().registerConcurrencyStrategy(new RequestContextHystrixConcurrencyStrategy());}
          在需要获取请求头信息的地方使用
          public static String getToken() { ServletRequestAttributes requestAttributes = requestAttributes(); if (requestAttributes != null) { return requestAttributes.getRequest().getHeader("Authorization"); } return null;}private static ServletRequestAttributes requestAttributes() { return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();}


          IP属地:四川5楼2022-05-12 16:30
          收起回复
            贴吧没格式,看起来太恼火了。下面的链接是有道云的,访问能看着舒服点
            http://note.youdao.com/noteshare?id=73dd026e69e68249ae9bf4117ae14e17


            IP属地:四川6楼2022-05-12 16:45
            收起回复
              内部的调用应该都是可信的,为什么还在hreader加东西


              IP属地:上海来自Android客户端8楼2022-05-13 10:53
              收起回复
                用信号量模式


                IP属地:重庆来自iPhone客户端9楼2022-05-13 19:15
                回复
                  有两种解法。第一个就是那个豪猪自定义线程池。第二个是用阿里那个threadlocal框架,可以开启新的线程也能把threadlocal透传到子线程。


                  IP属地:广东来自Android客户端10楼2022-05-14 19:01
                  回复