问题:com.netflix.hystrix.exception.HystrixTimeoutException: null 大概意思就是报熔断超时

文章描述了A服务通过Feign调用B服务时遇到HystrixTimeoutException的问题,解决方法包括调整A服务的Hystrix超时时间和Ribbon的连接超时时间,以及关注熔断机制的配置以优化请求响应时间。

问题出现的原因:

  我在A服务调用B服务的删除逻辑时,发现  B服务  正在给我返回成功的状态码时候,A服务 就开始报:com.netflix.hystrix.exception.HystrixTimeoutException: null

我的源码为:

A服务的service:

 

@Override
public String deleteById(List<Long> ids) {
    CommonResult commonResult = softwareFeign.forceDelete(ids);
    if(commonResult.getCode()==200L){
        LambdaQueryWrapper<PublisherSoftware> publisherSoftwareLambdaQueryWrapper = new LambdaQueryWrapper<>();
        publisherSoftwareLambdaQueryWrapper.in(PublisherSoftware::getSoftwareId, ids);
        publisherSoftwareMapper.delete(publisherSoftwareLambdaQueryWrapper);
    }else {
        Asserts.fail(ResultCode.FAILED);
    }
   return ResultCode.SUCCESS.getMessage();
}

A服务 feign的接口:

 

@FeignClient(name = "fast-download-platform",url = "localhost:8220",fallbackFactory = SoftwareFeignFallbackFactory.class)
public interface SoftwareFeign {
    //新增修改
    @RequestMapping(value = "/software/detail/saveOrUpdate", method = RequestMethod.POST)
    CommonResult saveOrUpdate(@RequestBody SoftwareDetailDto softwareDetail);

    //软件上下架
    @RequestMapping(value = "/software/detail/shelf", method = RequestMethod.POST)
    CommonResult softwareDetailShelfStatus(@RequestBody SoftwareCheckDto softwareCheckDto);

    //软件删除
    @RequestMapping(value = "/software/detail/forceDelete/{ids}", method = RequestMethod.DELETE)
    CommonResult forceDelete(@PathVariable("ids") List<Long> ids);

B服务的controller接口:

@RestController
@RequestMapping("/software/detail")
@ApiModel(value = "软件基础信息管理", description = "软件基础信息管理")
@Api(tags = "软件基础信息管理")
public class SoftwareDetailController {

    @Autowired
    private ISoftwareDetailService softwareDetailService;


    /**
     * 通过id删除,并强制删除其关联的数据
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "通过id强制删除,并强制删除其关联的数据")
    @RequestMapping(value = "/forceDelete/{ids}", method = RequestMethod.DELETE)
    public CommonResult forceDelete(@ApiParam(value = "软件id" , required = true) @PathVariable("ids") List<Long> ids) {
        softwareDetailService.softwareDetailForceDelete(ids);
        return CommonResult.success(ResultCode.SUCCESS);
    }

A服务的yml配置:

server:
  port: 8260
spring:
  application:
    name: fast-download-publish
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
  profiles:
    active: dev
  servlet:
    multipart:
      enabled: true #开启文件上传
      max-file-size: 2048MB #限制文件上传大小为10M
      max-request-size: 1MB
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启日志输出
feign:
  okhttp:
    enabled: true
  circuitbreaker:
    enabled: true
  client:
    config:
      default:
        connectTimeout: 6000
        readTimeout: 6000
        loggerLevel: basic

上面的代码  是会报 com.netflix.hystrix.exception.HystrixTimeoutException: null错误的,这个错误,你可以在你A服务的熔断里面打印出来,具体为:

 最开始错误的解决办法:

直接调试

这是错误的,我们应该关注错误的本身: com.netflix.hystrix.exception.HystrixTimeoutException: null  说的HystrixTimeoutException的异常

那么解决办法来了
在A服务的yml配置中添加

#hystrix的超时时间
hystrix:
  command:
    default:
      execution:
        timeout:
          enabled: true
        isolation:
          thread:
            #设置请求超时时间,默认5秒,超过指定的时间后,触发服务熔断
            timeoutInMilliseconds: 50000

最好再配置一下负载均衡:

 

ribbon:
  # 指的是建立连接后从服务器读取到可用资源所用的时间
  ReadTimeout: 6000
  # 指的是建立连接所用的时间,适用于网络状态正常的情况下,两端连接所用的时间
  ConnectTimeout: 6000

最终的    A服务    配置为:

 

 

 

 

### com.netflix.hystrix.exception.HystrixRuntimeException 异常的原因及解决方法 #### 1. 异常原因分析 `com.netflix.hystrix.exception.HystrixRuntimeException` 是 Hystrix 库抛出的运行时异常,通常发生在以下几种场景中: - **服务降级**:当服务不可用或响应超时时,Hystrix 会触发降级逻辑。如果降级逻辑本身也失败,则会抛出该异常[^2]。 - **超时**:Hystrix 命令执行时间超过配置的超时时间(`timeoutInMilliseconds`),则会触发超时异常并抛出此错误[^3]。 - **熔断器打开**:当请求失败率超过设定阈值时,Hystrix熔断器会打开,阻止后续请求直接调用服务,并可能抛出该异常[^5]。 #### 2. 解决方案 以下是针对上述原因的具体解决方案: ##### (1) 配置超时时间 通过调整 Hystrix 和 Ribbon 的超时时间,可以有效避免因超时导致的异常。在微服务的 `application.yml` 文件中添加以下配置: ```yaml hystrix: command: default: execution: isolation: thread: timeoutInMilliseconds: 6000 # 设置 Hystrix 超时时间为 6 秒 ribbon: ReadTimeout: 60000 # 设置 Ribbon 请求处理的超时时间为 60 秒 ConnectTimeout: 60000 # 设置 Ribbon 请求连接的超时时间为 60 秒 MaxAutoRetries: 0 # 当前实例重试次数为 0 MaxAutoRetriesNextServer: 1 # 切换到其他实例时重试次数为 1 ``` 通过上述配置,可以显著减少因超时引发的异常。 ##### (2) 检查降级逻辑 确保 Hystrix 命令的降级逻辑(Fallback)实现正确且不会抛出异常。例如,在定义 Hystrix 命令时,应提供一个可靠的降级方法: ```java public class ExampleCommand extends HystrixCommand<String> { private final String name; public ExampleCommand(String name) { super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup")); this.name = name; } @Override protected String run() throws Exception { // 正常业务逻辑 return "Hello " + name; } @Override protected String getFallback() { // 降级逻辑 return "Fallback: Hello " + name; } } ``` 如果降级逻辑本身也失败,则会导致 `HystrixRuntimeException` 抛出。因此,必须确保降级逻辑足够健壮。 ##### (3) 检查熔断器状态 当熔断器打开时,所有请求将被直接拒绝,从而可能导致异常。可以通过以下方式检查和调整熔断器的配置: - **熔断器开启条件**:默认情况下,当请求失败率达到 50% 且窗口期内的请求数量超过 20 时,熔断器会打开。 - **调整配置**:可以通过修改 `circuitBreaker.requestVolumeThreshold` 和 `circuitBreaker.errorThresholdPercentage` 来调整熔断器的敏感度。 示例配置如下: ```yaml hystrix: command: default: circuitBreaker: requestVolumeThreshold: 10 # 窗口期内的最小请求数量 errorThresholdPercentage: 50 # 失败率阈值 sleepWindowInMilliseconds: 5000 # 熔断器关闭等待时间 ``` ##### (4) 检查依赖注入 如果使用了 `RestTemplate` 进行服务调用,确保其正确配置为负载均衡版本。例如,取消注释以下代码片段并正确注入: ```java @Bean @LoadBalanced public RestTemplate getRestTemplate() { return new RestTemplate(); } ``` 如果没有正确配置 `@LoadBalanced`,可能会导致请求无法正确路由,从而引发异常[^4]。 #### 3. 总结 `com.netflix.hystrix.exception.HystrixRuntimeException` 的根本原因包括超时、降级失败和熔断器打开等。通过合理配置 Hystrix 和 Ribbon 的超时时间、完善降级逻辑以及调整熔断器参数,可以有效解决该异常。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值