Spring Cloud(四) Hystrix

服务容错保护: Spring Cloud Hystrix

  在微服务架构中,我们将系统拆分为很多服务单元,因为各单元的应用间通过服务注册与订阅的方式相互依赖,并且各单元运行在不同的进程中,因此有可能因为网络原因或者自己问题出现调用服务故障或者延迟。随着服务数量的增加,故障亦随之累加,最后导致自身服务的瘫痪。为了解决这种问题,出现了断路器等一系列的保护机制。而Spring Cloud Hystrix就实现了断路器、线程隔离等一系列系统保护功能,为系统的延迟和故障提供更加强大的容错能力。

实现容错保护

  1. 引入POM依赖

    1
    2
    3
    4
    5
    <!--Hystrix依赖-->
    <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    </dependency>
  2. 修改java类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    //启动类 RibbonconsumerApplication.java

    @SpringBootApplication
    @EnableDiscoveryClient //开启服务发现功能
    @EnableCircuitBreaker //开启断路器功能
    //@SpringCloudApplication //该注释包含了以上三个注释(一个SpringCloud标准应用包含服务发现以及断路器)
    public class RibbonconsumerApplication {
    public static void main(String[] args) {
    SpringApplication.run(RibbonconsumerApplication.class, args);
    }
    }

    //Service层 service/impl/HelloServiceImpl.java
    @Service
    public class HelloServiceImpl implements HelloService {
    private final
    RestTemplate restTemplate;

    @Autowired
    public HelloServiceImpl(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
    }

    @Override
    @HystrixCommand(fallbackMethod = "helloFallback")
    public String helloService() {
    return restTemplate.getForEntity("http://hello-service/hello", String.class).getBody();
    }

    public String helloFallback() {
    return "error";
    }
    }

    //Controller controller/ConsumerController.java
    @RestController
    public class ConsumerController {
    private final
    RestTemplate restTemplate;

    private final
    HelloService helloService;

    @Autowired
    public ConsumerController(RestTemplate restTemplate, HelloService helloService) {
    this.restTemplate = restTemplate;
    this.helloService = helloService;
    }

    @RequestMapping(value = "/ribbon-consumer", method = RequestMethod.GET)
    public String helloConsumer() {
    return restTemplate.getForEntity("http://hello-service/hello", String.class).getBody();
    }

    @RequestMapping(value = "/ribbon-consumer-hello-service", method = RequestMethod.GET)
    public String helloConsumerByHelloService() {
    return helloService.helloService();
    }

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {

    return "Hello World";
    }
    }