2.4 熔断器 - 2.4.1. Hystrix

优质
小牛编辑
135浏览
2023-12-01

Hystrix

在Spring Cloud中使用了Netflix开发的Hystrix来实现熔断器。下面我们依然通过几个简单的代码示例,进入Hystrix的学习:

通用方式使用Hystrix

代码示例:

新建一个Maven项目,在pom.xml中添加如下内容:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <artifactId>microservice-consumer-movie-ribbon-with-hystrix</artifactId>
  6. <packaging>jar</packaging>
  7. <parent>
  8. <groupId>com.itmuch.cloud</groupId>
  9. <artifactId>spring-cloud-microservice-study</artifactId>
  10. <version>0.0.1-SNAPSHOT</version>
  11. </parent>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-starter-eureka</artifactId>
  16. </dependency>
  17. <!-- 整合ribbon -->
  18. <dependency>
  19. <groupId>org.springframework.cloud</groupId>
  20. <artifactId>spring-cloud-starter-ribbon</artifactId>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework.boot</groupId>
  24. <artifactId>spring-boot-starter-actuator</artifactId>
  25. </dependency>
  26. <!-- 整合hystrix -->
  27. <dependency>
  28. <groupId>org.springframework.cloud</groupId>
  29. <artifactId>spring-cloud-starter-hystrix</artifactId>
  30. </dependency>
  31. </dependencies>
  32. </project>

启动类:MovieRibbonHystrixApplication.java,使用@EnableCircuitBreaker注解开启断路器功能:

  1. /**
  2. * 使用@EnableCircuitBreaker注解开启断路器功能
  3. * @author eacdy
  4. */
  5. @SpringBootApplication
  6. @EnableDiscoveryClient
  7. @EnableCircuitBreaker
  8. public class MovieRibbonHystrixApplication {
  9. /**
  10. * 实例化RestTemplate,通过@LoadBalanced注解开启均衡负载能力.
  11. * @return restTemplate
  12. */
  13. @Bean
  14. @LoadBalanced
  15. public RestTemplate restTemplate() {
  16. return new RestTemplate();
  17. }
  18. public static void main(String[] args) {
  19. SpringApplication.run(MovieRibbonHystrixApplication.class, args);
  20. }
  21. }

实体类:User.java

  1. public class User {
  2. private Long id;
  3. private String username;
  4. private Integer age;
  5. ...
  6. // getters and setters
  7. }

Hystrix业务类:RibbonHystrixService.java,使用@HystrixCommand注解指定当该方法发生异常时调用的方法

  1. @Service
  2. public class RibbonHystrixService {
  3. @Autowired
  4. private RestTemplate restTemplate;
  5. private static final Logger LOGGER = LoggerFactory.getLogger(RibbonHystrixService.class);
  6. /**
  7. * 使用@HystrixCommand注解指定当该方法发生异常时调用的方法
  8. * @param id id
  9. * @return 通过id查询到的用户
  10. */
  11. @HystrixCommand(fallbackMethod = "fallback")
  12. public User findById(Long id) {
  13. return this.restTemplate.getForObject("http://microservice-provider-user/" + id, User.class);
  14. }
  15. /**
  16. * hystrix fallback方法
  17. * @param id id
  18. * @return 默认的用户
  19. */
  20. public User fallback(Long id) {
  21. RibbonHystrixService.LOGGER.info("异常发生,进入fallback方法,接收的参数:id = {}", id);
  22. User user = new User();
  23. user.setId(-1L);
  24. user.setUsername("default username");
  25. user.setAge(0);
  26. return user;
  27. }
  28. }

controller:RibbonHystrixController.java

  1. @RestController
  2. public class RibbonHystrixController {
  3. @Autowired
  4. private RibbonHystrixService ribbonHystrixService;
  5. @GetMapping("/ribbon/{id}")
  6. public User findById(@PathVariable Long id) {
  7. return this.ribbonHystrixService.findById(id);
  8. }
  9. }

application.yml

  1. server:
  2. port: 8011
  3. spring:
  4. application:
  5. name: microservice-consumer-movie-ribbon-with-hystrix
  6. eureka:
  7. client:
  8. serviceUrl:
  9. defaultZone: http://discovery:8761/eureka/
  10. instance:
  11. hostname: ribbon # 此处,preferIpAddress不设置或者设为false,不能设为true,否则影响turbine的测试。turbine存在的问题:eureka.instance.hostname一致时只能检测到一个节点,会造成turbine数据不完整

验证:

  1. 启动注册中心:microservice-discovery-eureka

  2. 启动服务提供方:microservice-provider-user

  3. 启动服务消费方:microservice-consumer-movie-ribbon-with-hystrix

  4. 访问:http://localhost:8011/ribbon/1,获得结果:{"id":1,"username":"Tom","age":12}

  5. 关闭服务提供方:microservice-provider-user,访问http://localhost:8011/ribbon/1,获得结果:{"id":-1,"username":"default username","age":0},另外日志打印:c.i.c.s.u.service.RibbonHystrixService : 异常发生,进入fallback方法,接收的参数:id = 1

注意:

  1. 本示例代码在microservice-consumer-movie-ribbon基础上修改而来
  2. 如对本示例涉及的知识点有疑难,请查看上一章《服务消费者》

代码地址(任选其一):

  1. http://git.oschina.net/itmuch/spring-cloud-study/tree/master/microservice-consumer-movie-ribbon-with-hystrix
  2. https://github.com/eacdy/spring-cloud-study/tree/master/microservice-consumer-movie-ribbon-with-hystrix

Feign使用Hystrix

代码示例

在Feign中使用Hystrix是非常简单的事情,因为Feign已经集成了Hystrix。我们使用microservice-consumer-movie-feign-with-hystrix项目的代码做一点修改,将其中的UserClient.java修改为如下即可:

  1. /**
  2. * 使用@FeignClient注解的fallback属性,指定fallback类
  3. * @author eacdy
  4. */
  5. @FeignClient(name = "microservice-provider-user", fallback = HystrixClientFallback.class)
  6. public interface UserFeignHystrixClient {
  7. @RequestMapping("/{id}")
  8. public User findByIdFeign(@RequestParam("id") Long id);
  9. /**
  10. * 这边采取了和Spring Cloud官方文档相同的做法,将fallback类作为内部类放入Feign的接口中,当然也可以单独写一个fallback类。
  11. * @author eacdy
  12. */
  13. @Component
  14. static class HystrixClientFallback implements UserFeignHystrixClient {
  15. private static final Logger LOGGER = LoggerFactory.getLogger(HystrixClientFallback.class);
  16. /**
  17. * hystrix fallback方法
  18. * @param id id
  19. * @return 默认的用户
  20. */
  21. @Override
  22. public User findByIdFeign(Long id) {
  23. HystrixClientFallback.LOGGER.info("异常发生,进入fallback方法,接收的参数:id = {}", id);
  24. User user = new User();
  25. user.setId(-1L);
  26. user.setUsername("default username");
  27. user.setAge(0);
  28. return user;
  29. }
  30. }
  31. }

这样就完成了,是不是很简单呢?测试过程类似通用方式。

注意:

  1. 本示例代码在microservice-consumer-movie-feign基础上修改而来
  2. 如对本示例涉及的知识点有疑难,请查看上一章《服务消费者》

代码地址(任选其一)

  1. http://git.oschina.net/itmuch/spring-cloud-study/tree/master/microservice-consumer-movie-feign-with-hystrix
  2. https://github.com/eacdy/spring-cloud-study/tree/master/microservice-consumer-movie-feign-with-hystrix

参考文档:

  1. https://msdn.microsoft.com/en-us/library/dn589784.aspx
  2. http://martinfowler.com/bliki/CircuitBreaker.html
  3. http://particular.net/blog/protect-your-software-with-the-circuit-breaker-design-pattern
  4. https://github.com/Netflix/Hystrix/wiki/How-it-Works
  5. https://segmentfault.com/a/1190000005988895