spring cloud Uses Hystrix to implement fallback for a single method
- 2021-01-03 20:54:46
- OfStack
This article introduces spring cloud- fallback that uses Hystrix to implement a single method. It is shared as follows:
1. Add Hystrix dependencies
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
2. Write Controller
package com.chhliu.springboot.restful.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.chhliu.springboot.restful.feignclient.UserFeignClient;
import com.chhliu.springboot.restful.vo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
@RestController
public class RestTemplateControllerHystrixCommand {
@Autowired
private UserFeignClient client; // use Feign To consume Restful service
@GetMapping("/get/{id}")
@HystrixCommand(fallbackMethod="findByIdFallback")// use HystrixCommand Annotations, fallbackMethod Property to specify fallback The method of
public User findById(@PathVariable Long id) {
return client.findById(id);
}
// overwrite fallbackMethod Note that the return value of this method, parameters must be the same as the original method 1 to
public User findByIdFallback(Long id){
User u = new User();
u.setName("zhangsan");
u.setUsername("chhliu");
u.setId(9L);
return u;
}
}
3. Add Hystrix support to the startup class
@EnableCircuitBreaker
4. Add configuration files
server.port:7904
# spring boot Service registration to Eureka Server The name of the application
spring.application.name=springboot-rest-template-feign-hystrix
eureka.instance.prefer-ip-address=true
# Eureka Server Register the address of the service
eureka.client.service-url.defaultZone=http://chhliu:chhliu123456@localhost:8764/eureka
springboot-h2.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RetryRule
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 1 # In order to test Hystrix the fallback Effect, where the timeout is set to 1 ms
5. Test
In the browser input: http: / / localhost: 7904 / get / 2
The test results are as follows:
[
{"id":9,"username":"chhliu","name":"zhangsan","age":null,"balance":null}
As you can see from the above test results, the connection timeout went directly to the fallback method.