一、Hystrix简介
在分布式系统中,服务出险故障是不可避免的。Hystrix的目的是隔离远程系统、服务或者其他远程访问。防止级联故障,并且在分布式系统中实现故障恢复能力。
二、Hystrix的简单使用
2.1 在Ribbon+RestTemplate中使用Hystrix
在项目consulclient3中添加依赖
<!--断路器依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
修改启动入口程序
@SpringBootApplication
@EnableDiscoveryClient
@RestController
@Configuration
@EnableCircuitBreaker//使用断路器功能
public class ConsulClient3App {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Autowired
private RestTemplate restTemplate;
private static final String SERVICE_ID = "consulservice3";
@RequestMapping(value = "/say")
@HystrixCommand(fallbackMethod = "defaultSay")//使用断路功能,服务不可用,或者超时会调用defaultSay方法
public String sayService() throws InterruptedException {
return restTemplate.getForObject("http://"+SERVICE_ID+"/say",String.class);
}
private String defaultSay(){
return "service " + SERVICE_ID +" not available";
}
public static void main(String[] args){
SpringApplication.run(ConsulClient3App.class, args);
}
}
运行springboot应用程序,同时在8002和8001端口启动consulservcie3,调用接口localhost:9999/say,,正常情况下会两个端口的服务都可以调通
关闭8002端口的consulservcie3,再多次调用接口localhost:9999/say就会发现,出险下图情况,不会在调用8002端口的服务
2.2 在Feign中使用Hystrix
在项目consulclient4中添加依赖
<!--断路器依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
配置启动断路器
#作用是启用Hystrix
feign.hystrix.enabled=true
启动入口类添加注解
//用注解作用是使用Hystrix
@EnableCircuitBreaker
创建fallback类
@Component//此注解必须要
public class FallbackSayService implements SayService{
@Override
public String say() {
return “service not available”;
}
}
//FeignClient中使用fallback类
@FeignClient(value = "consulservice3",fallback = FallbackSayService.class)
public interface SayService {
@RequestMapping(value = "say")
String say();
}
运行springboot应用程序,同时在8002和8001端口启动consulservcie3,调用接口localhost:9999/say,正常情况下会两个端口的服务都可以调通,关闭其中一个服务就会出险如下截图所示