SpringCloud | 4.容错处理(Hystrix)
2019-07-02 本文已影响0人
海边的小溪鱼
在微服务架构中,一个请求需要调用多个服务是非常常见的,如下图:
较底层的服务如果出现故障,会导致连锁故障。当对特定的服务的调用的不可用达到一个阀值(Hystric 是5秒20次) 断路器将会被打开。
断路打开后,可用避免连锁故障,fallback方法可以直接返回一个固定值。
在ribbon使用断路器
引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
@EnableHystrix注解开启Hystrix
@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
/**
* @EnableHystrix 开启Hystrix
* */
public class RbbionApp {
public static void main(String[] args) {
SpringApplication.run(RbbionApp.class,args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
@HystrixCommand
Service方法上加上@HystrixCommand注解。该注解对该方法创建了熔断器的功能,并指定了fallbackMethod熔断方法,熔断方法直接返回了一个字符串,字符串为"hi,"+name+",sorry,error!",代码如下:
@Service
public class TestService {
@Autowired
RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "hiError")
public String hiService(String name) {
return restTemplate.getForObject("http://eureka-service/hi?name="+name,String.class);
}
public String hiError(String name) {
return "hi,"+name+",sorry,error!";
}
}
启动 ribbon-service 项目,访问http://localhost:8763/hi?name=gaolei
此时关闭 ribbon-service 项目,访问http://localhost:8763/hi?name=gaolei:
此刻停止eureka-service_工程,访问_http://localhost:8765/hi?name=gaolei
image