Spring Cloud常见问题与总结(二)

版权声明:本文为博主原创文章,可自由转载、引用,但需注明文章出处。 https://blog.csdn.net/StarskyBoy/article/details/83624764

在使用Spring Cloud的过程中,难免会遇到一些问题。所以对Spring Cloud的常用问题做一些总结。

一、整合Hystrix后首次请求失败

1.1 原因分析

    Hystrix 默认的超时时间是1秒,如果在1秒内得不到响应,就会进入 fallback 逻辑。由于 Spring 的懒加载机制,首次请求往往会比较慢,因此在某些机器(特别是配置低的机器)上,首次请求需要的时间可能就会大于1秒。

1.2 解决方案

    有很多方式解决该问题,下面列举几种比较简单的方案:

1) 方法一:为Ribbon配置饥饿加载。

ribbon:
  eager-load:
    enabled: true
    clients: client1,client2

对于Zuul:

zuul:
  ribbon:
    eager-load:
      enabled: true

2) 方法二:延长 Hystrix 的超时时间,示例如下

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds:5000

 该配置让 Hystrix 的超时时间改为5秒。

3) 方法三:禁用 Hystrix 的超时,示例如下

hystrix.command.default.execution.timeout.enabled: false

4) 方法四:对于 Feign , 还可以为 Feign 禁用 Hystrix , 示例如下

feign.hystrix.enabled: false

这样即可为 Feign 全局禁用 Hystrix 支持。但该方式比较极端,一般不建议使用。

二、Turbine 聚合数据不完整

   在某些版本的Spring Cloud (例如 Brixton SR5)中,Turbine 会发生该问题。该问题的直接观体现是:
使用 Turbine 聚合多个微服务,但在 Hystrix Dashboard 上只能看到部分微服务的监控数据。

    现象描述:

    比如 Turbine 配置如下:

turbine:
  appConfig:cloud-consumer-movie,cloud-consumer-movie-feign-hystrix-fallback-stream
  clusterNameExpression:"'default'"

  Turbine 理应聚合 cloud-consumer-movie,cloud-consumer-movie-feign-hystrix-fallback-stream 这两个微服务的监控数据,然而打开 Hystrix Dashboard 时,会发现Dashboard 上只显示部分微服务的监控数据。

    解决方案:

    当 Turbine 聚合的微服务部署在同一台主机上时,就会出现该问题。

    解决方案一:

    为各个微服务配置不同的 hostname ,并将 preferIpAddress 设为 false 或者不设置。

eureka:
  client:
    serviceUrl:
	  defaultZone:http://127.0.0.1:8001/eureka/
  instance:
    hostname:ribbon # 配置hostname

  解决方案二:

    设置turbine.combine-host-port = true

turbine:
  appConfig: cloud-consumer-movie,cloud-consumer-movie-feign-hystrix-fallback-stream
  clusterNameExpression:"'default'"
  combine-host-port:true

    方法三:
    升级 Spring Cloud 到 Camden 或更新版本。当然,也可单独升级 Spring Cloud Netflix 到 1.2.0以上最新稳定版(一般不建议单独升级 Spring Cloud Netflix, 因为可能会跟 Spring Cloud 其他组件冲突)。

    这是因为老版本中的 turbine.combine-host-port 默认值是 false 。Spring Cloud 已经意识到该问题,故在新的版本中将该属性的默认值设为 true 。该解决方案和方法二本质是一致的。

相关代码

org.springframework.cloud.netflix.turbine.TurbineProperties.combine-HostPort

org.springframework.cloud.netflix.turbine.CommonsInstanceDiscovery.getInstance(String, String, String, Boolean)

更多精彩内容,请关注博主公众号

猜你喜欢

转载自blog.csdn.net/StarskyBoy/article/details/83624764