SpringCloud Hystrix的使用

目录
  • 简介
  • 服务熔断
    • 实践
  • 服务降级
    • 实践
      • 服务熔断与服务降级的区别
        • 服务监控 Dashboard
          • 建立项目

        简介

        在分布式系统中,服务与服务之间依赖错综复杂,一种不可避免的情况就是某些服务将会出现失败。Hystrix是一个库,它提供了服务与服务之间的容错功能,主要体现在延迟容错和容错,从而做到控制分布式系统中的联动故障。Hystrix通过隔离服务的访问点,阻止联动故障,并提供故障的解决方案,从而提高了这个分布式系统的弹性。

        面对的问题: 一个应用一般会依赖多个服务,每个服务由于网络不可靠,机房的不可靠等等不稳定的因素,总会导致服务的故障,如果我们不对这些故障做处理,就会进而导致整个系统的不可用。

        服务雪崩:

        一个正常的用户进入调用微服务A然后调用B在调用C然后离开,而当其中微服务C出现故障,导致用户停留
        B,越来越多的用户进入,请求,停留B在最终导致B的资源被耗尽,不可用,进而A也慢慢不可用。这一系
        列链式反应就像雪崩一样影响越来越大,称为"服务雪崩"

        服务熔断

        参考:www./article/166784.htm

        应对雪崩效应的一种微服务链路保护机制

        当调用链路的某个微服务不可用或者响应时间太长时,会进行服务熔断,不再有该节点微服务的调用,快速返回错误的响应信息。当检测到该节点微服务调用响应正常后,恢复调用链路。

        在Spring Cloud中通过Hystrix实现。Hystrix会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是5秒内20次调用失败,就会启动熔断机制。

        服务熔断解决如下问题:

        1. 当所依赖的对象不稳定时,能够起到快速失败的目的;
        2. 快速失败后,能够根据一定的算法动态试探所依赖对象是否恢复

        实践

        项目搭建

        根据 实验环境搭建中的项目copy建立一个新模块名为springcloud-provider-dept-hystrix。

        导入依赖

         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-hystrix</artifactId>
             <version>1.4.6.RELEASE</version>
        </dependency>
        

        使用

        在Controller层,使用@HystrixCommand来实现熔断

        @Target({ElementType.METHOD})
        @Retention(RetentionPolicy.RUNTIME)
        @Inherited
        @Documented
        public @interface HystrixCommand {
            String groupKey() default "";
            String commandKey() default "";
            String threadPoolKey() default "";  
            String fallbackMethod() default "";
            HystrixProperty[] commandProperties() default {};
            HystrixProperty[] threadPoolProperties() default {};
            Class<? extends Throwable>[] ignoreExceptions() default {};
            ObservableExecutionMode observableExecutionMode() default ObservableExecutionMode.EAGER;
            HystrixException[] raiseHystrixExceptions() default {};
            String defaultFallback() default "";
        }
        
        
        

        在@HystrixCommand中有 defaultFallback() 指定默认的备用方法(default ""), fallbackMethod() 指定失败后进行的备用方法(default "")

        当正常的方法调用失败后(5秒内20次调用失败),认为是出故障了就进行熔断,快速返回错误信息(调用备选方法)。

        @RestController
        public class DeptController {
            @Autowired
            private DeptImpl deptimpl;
            @RequestMapping("/dev/{id}")
            @HystrixCommand(fallbackMethod = "HystrixGet")//指明备用方法
            public Dept DeptqueryByID(@PathVariable("id") Long id) {
                Dept dept = deptimpl.queryByID(id);
                System.out.println(dept);
                if (dept==null) {
                    throw new RuntimeException("id--->" + id + "用户不存在");
                }
                return dept;
            }
            public Dept HystrixGet(@PathVariable("id") Long id) {
                Dept dept=new Dept();
                dept.setDeptnumber(id.intValue());
                dept.setDname("id"+id+"用户不存在");
                dept.setD_source("no~~~~~~");
                return dept;
            }
        
        }
        

        在启动类上添加@EnableCircuitBreaker开启熔断支持

        @SpringBootApplication
        @EnableEurekaClient
        @EnableCircuitBreaker//开启熔断支持
        public class HApplication {
            public static void main(String[] args) {
                SpringApplication.run(HApplication.class,args);
            }    
        }
        

        服务降级

        即在服务器压力剧增的情况下,关闭一些很少被调用的服务,腾出一些资源,保证正常运行。

        如淘宝双十一关闭退款通道。

        实践

        在原本的FeignClient指明fallbackFactory

        @FeignClient(value = "PROVIDER-NAME",fallbackFactory = SerciceFallbackFactory.class)
        public interface DeptClientService {
            @RequestMapping(value = "/dev/add")
            boolean add(Dept dept);
        
            @RequestMapping(value = "/dev/{id}")
            Dept queryByID(@PathVariable("id") Long id );
        
            @PostMapping(value = "/dev/list")
            List<Dept> queryAll();
        }
        
        

        定义自己的FallbackFactory

        报错注意import feign.hystrix.FallbackFactory;

        import feign.hystrix.FallbackFactory;
        @Component
        public class SerciceFallbackFactory implements FallbackFactory {
        
            public DeptClientService create(Throwable cause) {
                return new DeptClientService() {
                    public boolean add(Dept dept) {
                        return false;
                    }
                    //定义返回的错误信息
                    public Dept queryByID(Long id) {
                        Dept dept = new Dept();
                        dept.setD_source("服务降级");
                        dept.setDname("fail");
                        dept.setDeptnumber(-1);
                        return dept;
                    }
        
                    public List<Dept> queryAll() {
                        return null;
                    }
                };
            }
        }
        

        在客户端的配置文件中添加

        #开启降级
        feign:
          hystrix:
            enabled: true
        

        结果:在我们关闭服务端后再次访问服务时

        服务熔断与服务降级的区别

        • 服务熔断是在服务端进行的,而服务降级是在客户端进行的
        • 服务熔断的原因:发生故障,服务降级:为整体负荷考虑,保证核心业务的运行

        服务监控 Dashboard

        建立项目

        导入依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        

        配置文件

        server:
          port: 9001
        hystrix:
          dashboard:
        # Hystrix Dashboard会通过proxyUrl解析到host部分,然后通过配置的proxyStreamAllowList。判定是否允许被访问
            proxy-stream-allow-list: "localhost" 
            
        

        开启监控支持

        @SpringBootApplication
        @EnableHystrixDashboard//开启
        @EnableDiscoveryClient
        public class DashboardApplication {
            public static void main(String[] args) {
                SpringApplication.run(DashboardApplication.class,args);
            }
        }
        

        运行后访问:http://localhost:9001/hystrix

        根据提示在spingcloud-provider-dept-hystrix服务端添加bean

        @Bean
            public ServletRegistrationBean hystrixMetricsStreamServlet(){
                ServletRegistrationBean servlet = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
                servlet.addUrlMappings("/actuator/hystrix.stream");
                return servlet;
            }
        

        运行后访问 http://localhost:8081/actuator/hystrix.stream 可以获得一些服务的信息

        注意: 需要调用一次标注有 @HystrixCommand 方法才会有数据显示,只会监控有 @HystrixCommand 的方法

        我们也可以通过在http://localhost:9001/hystrix 输入

        按下按钮开启对该服务的监控

        以上就是SpringCloud Hystrix的使用的详细内容,更多关于SpringCloud Hystrix的资料请关注其它相关文章!

        本文转自网络,如有侵权请联系客服删除。