In the previous article of this series, we demonstrated how to apply the Gateway’s current limiting function. In this article, we will demonstrate how to use Hystrix’s circuit breaker function.
Create a new microservice project
Create a new ordinary maven project in IDEA, name its groupId: cn.com.hohistar.tutorial and artifactId: springcloud-hystrix-service, and then replace the pom.xml of the project with the following::
In this example, we will build a class that accesses (consume) the todo-service created earlier, and uses the fuse mechanism in the methods of this class.。
New data class
Create a new package named: cn.com.hohistar.tutorial.springcloudhystrixservice.model in src/main/java, and add a class named: Todo in it, the code is as follows:
1 2 3 4 5 6 7 8 9 10
@Data publicclassTodo{
private Long id;
private String title;
private String desc;
}
Because all service returns are not standardized to the format of ApiResult, it is also necessary to add the definition of the ApiResult class in the model package. code show as below:
1 2 3 4 5 6 7 8 9 10 11
@Data publicclassApiResult<T> {
private Boolean succ;
private String code;
private String msg;
private T data; }
Define access service
Create a new package named: cn.com.hohistar.tutorial.springcloudhystrixservice.service in src/main/java, and add a new class named: HystrixedClientService in it, and fill in the following code:
@Bean @LoadBalanced public RestTemplate restTemplate(){
returnnew RestTemplate(); }
}
New API service
Create a new package named: cn.com.hohistar.tutorial.springcloudhystrixservice.api in src/main/java, and add a new class named: HystrixedClientController in it, and fill in the following code:
@GetMapping("/todo") public ApiResult< List<Todo> > getTodos() { return clientService.getTodos(); }
}
New startup class
Create a new package named: cn.com.hohistar.tutorial.springcloudhystrixservice in src/main/java, and add a new class named: SpringcloudHystrixServiceApplication in it, and fill in the following code:
Hystrix’s default timeout time is 1 second, that is, when the service consumer is waiting for the service provider to return information, if the return information is not received for more than 1 second, the service provider is considered to be faulty and the locally set downgrade strategy is directly executed, that is The method specified by fallbackMethod.
Therefore, we modify the todo-service project and add a mandatory delay of 20 seconds to the method of the TodoService class in the cn.com.hohistar.tutorial.springcloudtodoservice.service package. The modified code is as follows: