SpringCloud实战(四)-断路器(Hystrix)

本文是SpringCloud实战(四)-断路器(Hystrix),若要关注前文,请点击传送门:

SpringCloud实战(三)-服务间调用(Feign)

前文我们介绍了通过Feign实现服务间调用。在我们平常工作中有的时候难免会遇到服务不能提供相应或者发生宕机的情况存在,此时可能会造成线程close_wait的情况,造成CPU飙升100%,这种情况在SpringCloud中也给出了相应的微服务组件来进行处理,就是本文中将要介绍的断路器(Hystrix)。

一、Hystrix简介

Netflix开源了Hystrix组件,实现了断路器模式,SpringCloud对这一组件进行了整合。 在微服务架构中,一个请求需要调用多个服务是非常常见的,如下图:

HystrixGraph.png

较底层的服务如果出现故障,会导致连锁故障。当对特定的服务的调用的不可用达到一个阀值(Hystric 是5秒20次) 断路器将会被打开。

HystrixFallback.png

断路打开后,可用避免连锁故障,fallback方法可以直接返回一个固定值。

在分布式环境中,许多服务依赖项中的一些必然会失败。Hystrix是一个库,通过添加延迟容忍和容错逻辑,帮助你控制这些分布式服务之间的交互。Hystrix通过隔离服务之间的访问点、停止级联失败和提供回退选项来实现这一点,所有这些都可以提高系统的整体弹性。

Hystrix被设计的目标是:1、对通过第三方客户端库访问的依赖项(通常是通过网络)的延迟和故障进行保护和控制。2、在复杂的分布式系统中阻止级联故障。3、快速失败,快速恢复。4、回退,尽可能优雅地降级。5、启用近实时监控、警报和操作控制。

二、准备工作

这篇文章基于上一篇文章的工程,首先启动上一篇文章的工程,启动eureka-server 工程;启动service-hi工程,它的端口为8762。

三、单点断路器(Hystrix)

我们基于前文中的service-ribbon工程来进行hystrix的配置。

3.1 maven依赖

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

在service-ribbon的pom文件中追加hystrix依赖。

3.2 启动类(ServiceRibbonApplication)

@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
public class ServiceRibbonApplication {

    public static void main(String[] args) {
        SpringApplication.run( ServiceRibbonApplication.class, args);
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

3.3 Service层

@Service
public class HelloService {

    @Autowired
    RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
            }
    )
    public String hiService(String name) throws InterruptedException {
        long startTime = System.currentTimeMillis();    //获取开始时间
        String str = restTemplate.getForObject("http://service-hi/hi?name=" + name, String.class);
        long endTime = System.currentTimeMillis();    //获取结束时间
        System.err.println("耗时:" + (endTime - startTime));
        return str;
    }

    public String hiError(String name) {
        return "hi," + name + ",sorry,error!";
    }
}

我们配置了一个fallbackMethod和调用超时时间,当发生异常或者调用时间超过了3000ms的时候,该方法就会回调hiError(String name)进行返回。

访问 http://localhost:8764/hi?name=zzx

浏览器返回以下结果:

    service-ribbon:hi zzx ,i am from port:8762

此时我们关闭service-hi,再次访问 http://localhost:8764/hi?name=zzx

浏览器返回以下结果:

    service-ribbon:hi,zzx,sorry,error!

说明断路器生效。

四、Feign断路器(Hystrix)

hystrix不管能够配置在单节点上,也可以配置在Feign的服务间调用进行异常熔断,我们基于前文中的service-feign工程进行改造。

4.1 maven依赖

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

在service-feign的pom文件中追加hystrix依赖。

4.2 配置文件(application.yml)

eureka:
  client:
    serviceUrl:
      defaultZone: http://eureka-serve-01:8761/eureka/

server:
  port: 8765

spring:
  application:
    name: service-feign

management:
  endpoints:
    web:
      exposure:
        include: "*"

feign:
  hystrix:
    enabled: true

4.3 启动类(ServiceFeignApplication)

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
@EnableCircuitBreaker
public class ServiceFeignApplication {

    public static void main(String[] args) {
        SpringApplication.run( ServiceFeignApplication.class, args);
    }

    @Bean
    public ServletRegistrationBean getServlet(){
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}

需要注意这里和service-ribbon的不太一样,如果是Feign的断路器需要增加@EnableCircuitBreaker注解,同时需要注册ServletRegistrationBean到IOC容器中。

4.4 Controller层

@RestController
public class HelloController {

    @Resource
    ScheduleServiceHi scheduleServiceHi;

    @RequestMapping(value = "/hi")
    public String hi(@RequestParam String name){
        return "service-feign:" + scheduleServiceHi.sayHiFromClientOne(name);
    }
}

4.5 Service层

@FeignClient(value = "service-hi",fallback = SchedualServiceHiHystric.class)
public interface ScheduleServiceHi {

    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    String sayHiFromClientOne(@RequestParam(value = "name") String name);
}
@Component
public class SchedualServiceHiHystric implements ScheduleServiceHi {

    @Override
    public String sayHiFromClientOne(String name) {
        return "sorry " + name;
    }
}

启动service-feign工程,关闭service-hi实例,访问 http://localhost:8765/hi?name=zzx,得到浏览器返回结果如下:

    service-feign:sorry zzx

服务链路追踪(Spring Cloud Sleuth)

猜你喜欢

转载自blog.csdn.net/qq_19734597/article/details/90031416