springcloud系列15——hystrix简介及简单代码示例
Hystrix简介
在微服务中,有服务A、B,C,D4个微服务。其中,C依赖D,A和B依赖C。
那么当D出现问题时,会导致C不可用,进而导致A和B也不可用。这就是产生了雪崩效应。
hystrix语义为“豪猪”,它身上有很多刺,具有自我保护的能力。hystrix的出现即为解决雪崩效应。
关于Hystrix的原理可用参考:https://www.jianshu.com/p/e07661b9bae8。
spring cloud hystrix相关内容参考:http://cloud.spring.io/spring-cloud-static/Edgware.SR3/single/spring-cloud.html#_circuit_breaker_hystrix_clients。
简单代码示例
新增模块microservice-springcloud-movie-hystrix。该模块是从microservice-springcloud-movie拷贝过去的。
在pom.xml增加hystrix依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
在App启动类增加@EnableCircuitBreaker
注解:
@SpringBootApplication
@EnableCircuitBreaker
public class MovieHystrixApp {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main( String[] args )
{
SpringApplication.run(MovieHystrixApp.class,args);
}
}
Controller:
@RestController
public class MovieController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/user/{userId}")
@HystrixCommand(fallbackMethod = "getUserFallback")
public User getUser(@PathVariable Long userId) {
return restTemplate.getForObject("http://microservice-springcloud-user/sample/" + userId,User.class);
}
public User getUserFallback(Long userId) {
User user = new User();
user.setId(0L);
return user;
}
}
fallbackMethod
指定服务调用失败时的处理方法为getUserFallback。
注意:fallbackMethod指定的方法必须与原方法有相同的方法签名。
测试
1.启动EurekaServer App;
2.启动microservice-springcloud-user;
3.启动microservice-springcloud-movie-hystrix。
浏览器请求http://127.0.0.1:8761/。
第一次执行会发现调用了fallbackMethod指定的方法,返回的user的id为0.
后面刷新,返回的都是正常的调用user模块的。
我们将user服务关闭,再刷新页面。此时页面有一定的等待,并返回的是fallbackMethod指定的数据,user的id为0.
后面刷新页面20次,然后继续刷新,发现虽然返回的user的id还是0,但是没有等待。过几秒后,刷新页面又有等待,过一会儿又没有了。
原因在spring cloud的文档中已经说到:
A service failure in the lower level of services can cause cascading(级联) failure all the way up to the user. When calls to a particular service is greater than circuitBreaker(断路器).requestVolumeThreshold (default: 20 requests) and failue percentage is greater than circuitBreaker.errorThresholdPercentage (default: >50%) in a rolling window defined(定义) by metrics(度量标准).rollingStats.timeInMilliseconds (default: 10 seconds), the circuit(电路) opens and the call is not made. In cases of error and an open circuit a fallback(撤退) can be provided by the developer.
翻译过来的意思就是:
在较低级别的服务中的服务故障可能导致级联故障一直到用户。当对特定服务的调用大于circuitBreaker.requestVolumeThreshold(默认值:20请求)和故障率大于circuitBreaker.errorThresholdPercentage阈值百分比(默认值:50%)在metrics.rollingStats.timeInMilliseconds指定的时间内(默认10秒)。断路器打开并且不进行服务的调用。在错误和电路打开的情况下,开发人员可以提供回退。
所以,在10秒后,20次请求,有50%的故障率,Hystrix会执行开发人员提供的fallback方法。
但是Hystrix有它的监控方法,所以隔一定的时间(默认5秒),Hystrix会检查服务是否可用,如果不可用,则继续打开断路器开关,并按指定的回退方法处理;如果服务恢复正常,则执行服务调用。
还没有评论,来说两句吧...