feign集成hystrix获取不到RequestContextHolder.currentRequestAttributes()案例解决


1、问题描述

SpringBoot项目中使用到了feign作为Cloud平台内部微服务之间的接口调用,内部组件之间调用过程中,需要在RequestTemplate中添加请求头header鉴权等信息,而feign在开启了httpclient和hystrix支持后,发现RequestContextHolder.currentRequestAttributes()抛No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.异常。
yml引入feign、hystrix配置如下:

feign:
  httpclient:
    enabled: true
  hystrix:
    enabled: true
  compression: #开启GZIP
    request:
      enabled: true
    response:
      enabled: true

hystrix:
  threadpool:
    default:
      coreSize: 20  # 设置线程池大小为20
  metrics:
    enabled: true
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 60000
        timeout:
          enabled: false

2、问题分析

hystrix使用多线程管理请求连接池,从主线程到发送基于hystrix的feign请求线程已不在同一个线程内,而RequestContextHolder是基于ThreadLocal实现的,这就使得线程之间数据断链,需要通过线程之间的数据传递使得ThreadLocal中存储的currentRequestAttributes接上。hystrix强大在于是支持此扩展操作的。

3、通过HystrixConcurrencyStrategy自定义策略,解决线程间的数据传递

废话不多说,直接上代码:

package com.xx.xx.app.config;

import java.util.concurrent.Callable;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;

/**
 * @author zhouyuhhu
 * @date 2019/12/26
 */
public class RequestContextHystrixConcurrencyStrategy <
  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值