Hystrix的容错能力
    微服务必须非常可靠,因为它们彼此依赖。微服务架构包含大量的小型微服务。这些微服务相互通信以便满足其需求。
  
    微服务的实例可能会频繁地上下波动。
   随着微服务之间交互次数的增加,系统中微服务失败的机会也随之增加。
  
容错
    考虑一个场景,其中六个微服务相互通信。
    microservice-5 在某个时候关闭,所有其他微服务都直接或间接依赖于它,因此所有其他服务也都关闭了。
  
    此问题的解决方案是为了在微服务失败时使用
    fallback 。微服务的这一方面称为
   容错。
  
   
 
   容错可以借助
   断路器来实现。它是一种将请求包装到外部服务并检测它们何时失败的模式。如果检测到故障,则断路器断开。所有后续请求都立即返回错误,而不是向运行状况不佳的服务发出请求。它监视并检测已关闭的服务以及与其他服务行为不正常的服务。它会拒绝呼叫,直到呼叫恢复正常为止。
  
 Hystrix 
    Hystrix是一个库,用于控制微服务之间的交互以提供延迟和容错能力。此外,可以通过修改UI来让用户知道某些事情可能无法按预期工作或需要花费更多时间。
  
   使用Hystrix实现容错功能
  
   步骤1: 打开
    limits-service 的
    pom.xml 文件并添加Hystrix依赖项
  
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
 
   步骤2: 打开
    LimitsServicesApplication.java 文件,并使用注释
    @EnableHystrix启用 Hystrix 。
  
    LimitsServicesApplication.java 
  
package com.lidihuo.microservices.limitsservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
@SpringBootApplication
@EnableHystrix
public class LimitsServiceApplication 
{
public static void main(String[] args) 
{
SpringApplication.run(LimitsServiceApplication.class, args);
}
}
 
   步骤3: 打开
    LimitsConfigurationController.java 文件并创建一个
    Get 方法。
  
@GetMapping("/fault-tolerance-example")
//configuring a fallback method
@HystrixCommand(fallbackMethod="fallbackRetrieveConfigurations")
public LimitConfiguration retrieveConfigurations()
{
throw new RuntimeException("Not Available"); 
}
//defining the fallback method
public LimitConfiguration fallbackRetrieveConfigurations()
{
//returning the default configuration  
return new LimitConfiguration(999, 9); 
}
 
    让我们了解上述方法中发生的事情。
  
    在上述方法中,我们创建了Get映射以实现容错功能。在下一行中,我们使用了注释
    @HystrixCommand 来配置
    fallback 方法。我们定义了一个名称为
    fallbackRetrieveConfigurations()的方法,如果发生任何故障,该方法将返回默认值。
  
   回退方法
  
    fallback方法是在发生故障时调用的方法。 Hystrix允许我们为每种服务方法定义一个备用方法。这里出现一个问题,如果该方法引发异常,应该返回给使用者什么?
  
    所以答案是,如果
    retrieveConfiguraions()失败,则该方法
    fallbackRetrieveConfigurations()被调用。 fallback方法返回硬编码的
    LimitConfiguration 实例。
  
   步骤4: 打开浏览器并调用URL http://localhost:8080/fault-tolerance-example 。它返回我们在
    fallbackRetrieveConfigurations()方法中返回的值。
  
  