Greenwich.SR2版本的Spring Cloud Hystrix实例

时间:2019-07-20
本文章向大家介绍Greenwich.SR2版本的Spring Cloud Hystrix实例,主要包括Greenwich.SR2版本的Spring Cloud Hystrix实例使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

  之前我们在eureka(参见Greenwich.SR2版本的Spring Cloud Eureka实例)中,服务消费方a-beautiful-client调用服务提供方a-bootiful-client,如果这时提供方挂掉或者请求超时的话,如何实现服务降级呢?spring cloud给我们提供了Hystrix这个断路器,通过注解能很方便的实现。我们还是拿a-beautiful-client举例,老套路,三板斧亮出:

  1、pom里新增Hystrix的jar包引入:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

  2、主类添加@EnableCircuitBreaker注解开启熔断;

  3、实现类ConusmerServiceImpl添加@注解和降级方法:

    @Override
    @HystrixCommand(fallbackMethod = "backupCall")
    public String call(String name) {
        ResponseEntity resultResponseEntity = restTemplate.postForEntity(appServiceUrl + "hello?name=" + name, null, String.class);
        if (resultResponseEntity != null && resultResponseEntity.getBody() != null) {
            return name + " says: " + resultResponseEntity.getBody().toString();
        }
        return null;
    }

    public String backupCall(String name) {
        return "Hi, I'm Hystix.";
    }

  打完收工。我们把服务提供方a-bootiful-client的全部或部分服务停掉,再通过http://localhost:8763/sayHello?name=world请求,会发现返回的是服务降级方法backupCall里的东西了:

   我们上面是通过服务降级方法来实现的熔断,其实也可以通过服务降级类来做,详见Greenwich.SR2版本的Spring Cloud Feign实例

原文地址:https://www.cnblogs.com/wuxun1997/p/11217609.html