Hystrix circuit breaker
Hystrix is the circuit breaker tool of spring cloud. The so-called circuit breaker is if a business fails or
一旦断路器发现就断掉业务的接口路
goes down , then jump to our preset business or report an error prompt
hystrix(断路器) 直接调用在 ribbo(负载均衡) 里面
Features of Hystrix circuit breakers
1-downgrade
If there is an error in requesting the background service, you can execute another piece of code to return a response to the client
Downgrade response, which can be an error message or a cached database
If the downgrade code is implemented:
- @HystrixCommand(fallbackMethod = "Downgrade method")
- To implement the downgrade method, add downgrade code
2-Fuse
A server failure may cause an avalanche effect,
熔断可以快速断开故障服务,保护其他服务不受影响
Conditions for fusing
- 20 requests in 10 seconds (must be satisfied)
- 50% failed, degraded code executed
Half open
- 5 seconds after the circuit breaker is opened, it enters the half-open state
- Try a request,
-
- The request is successful, close the circuit breaker and automatically return to normal
-
- The request fails and the circuit breaker continues to remain open
Expansion (cause of avalanche)
Cause of
Corresponding measurement
Implement hystrix circuit breaker
Dependency (pom.xml)
xml way
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
Visualization
Modify application.yml
spring:
application:
name: hystrix
server:
port: 3001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
MaxAutoRetries: 1
MaxAutoRetriesNextServer: 2
OkToRetryOnAllOperations: true
只有改掉名字就行了
Main program
@EnableCircuitBreaker
Enable hystrix circuit breaker
To start the circuit breaker, the circuit breaker provides two core functions:
可以使用 @SpringCloudApplication 注解代替三个注解
//@EnableCircuitBreaker
//@EnableDiscoveryClient
//@SpringBootApplication
@SpringCloudApplication
public class Sp06RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(Sp06RibbonApplication.class, args);
}
@LoadBalanced
@Bean
public RestTemplate getRestTemplate() {
SimpleClientHttpRequestFactory f = new SimpleClientHttpRequestFactory();
f.setConnectTimeout(1000);
f.setReadTimeout(1000);
return new RestTemplate(f);
}
}
重点是添加注解就行了别的代码不重要
Add downgrade method to Controller
-
Add a downgrade method for each method, such as getItems() Add a downgrade method getItemsFB()
-
Add @HystrixCommand annotation, specify the name of the downgrade method
Code structure
@RestController
public class RibbonController {
@Autowired
private RestTemplate restTemplate;
@GetMapping ("/item-service/{orderId}")
@HystrixCommand(fallbackMethod = "getItemsFB") //远程调用失败 跳转到当前的方法
public JsonResult<List<Item>> getItems(@PathVariable String orderId){
return restTemplate.getForObject("http://item-service/{1}", JsonResult.class,orderId);
}
@HystrixCommand(fallbackMethod = "decreaseNumberFB") //远程调用失败 跳转到当前的方法
@PostMapping("/item-service/decreaseNumber")
public JsonResult<?> decreaseNumber(@RequestBody List<Item> items){
return restTemplate.postForObject("http://item-service/decreaseNumber", items, JsonResult.class);
}
//降级方法的参数和返回值,需要和原始方法一致,方法名任意
public JsonResult<List<Item>> getItemsFB(String orderId) {
return JsonResult.err("获取订单商品列表失败");
}
public JsonResult decreaseNumberFB(List<Item> items) {
return JsonResult.err("更新商品库存失败");
}
}
This is the demo code to explain the core of the circuit breaker, other codes are not important
Description: 当前业务的降级是getItemesFB方法
The method of getItems is getItemsFB
Description: When business
超时、出错、不可到达时,
starting corresponding downgrade method that returns an error message
hystrix timeout setting
Timeout After setting
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds
hystrix to wait for a timeout in yml, the downgrade code will be executed, and the downgrade result will be quickly returned to the client. The default timeout time is 1000 milliseconds
In order to test the degradation of hystrix, we set the hystrix wait timeout to be very small (500 milliseconds).
Important: This setting should generally be greater than the ribbon's retry timeout period, for example, 10 seconds
spring:
application:
name: hystrix
server:
port: 3001
eureka:
client:
service-url:
defaultZone: http://eureka1:2001/eureka, http://eureka2:2002/eureka
ribbon:
MaxAutoRetriesNextServer: 2
MaxAutoRetries: 1
OkToRetryOnAllOperations: true
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 500
Start the project for testing
hystrix fuse
The entire link reaches a certain threshold. By default, if more than 20 requests are generated within 10 seconds, the first condition is met.
When the first condition is met, if the requested error percentage is greater than the threshold, the circuit breaker will be opened, and the default is 50%.
Hystrix's logic first judges whether the first condition is met, and then judges the second condition. If both conditions are met, the circuit breaker will be turned on
- After the circuit breaker is opened for 5 seconds, it will be in a half-open state, and it will try to forward the request. If it still fails, keep it open, if it succeeds, close the circuit breaker