JAVAEE细细看 框架32 - SpringCloud 微服务(七) 熔断器 - Hystrix

Hystrix-概述

Hystrix 在英文里面的意思是 豪猪,它的logo 看下面的图是一头豪猪,它在微服务系统中是一款提供保护机制的组
件,和eureka一样也是由netflix公司开发。
主页:https://github.com/Netflix/Hystrix/

在这里插入图片描述

那么Hystrix的作用是什么呢?具体要保护什么呢?

• Hystix 是 Netflix 开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败(雪崩)。
• 雪崩:一个服务失败,导致整条链路的服务都失败的情形。

在这里插入图片描述
在这里插入图片描述

1. Hystrix-降级-提供方降级

Hystix 降级:当服务发生异常或调用超时,返回默认数据

在这里插入图片描述

提供方

  1. 在服务提供方,引入 hystrix 依赖

    <!--parent引入Spring Cloud 依赖-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
    
        </dependencies>
    </dependencyManagement>
    
    
    <!-- hystrix-provider 引入 hystrix -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    
  2. 定义降级方法

    /**
     * 定义降级方法:
     *  1. 方法的返回值需要和原方法一样
     *  2. 方法的参数需要和原方法一样
     */
    public Goods findOne_fallback(int id){
    	Goods goods = new Goods();
    	goods.setTitle("降级了~~~");
    	return goods;
    }
    
  3. 使用 @HystrixCommand 注解配置降级方法

    @GetMapping("/findOne/{id}")
    @HystrixCommand(fallbackMethod = "findOne_fallback",
    				commandProperties = {
    					//设置Hystrix的超时时间,默认1s
    		@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",
    		value = "3000")
    })
    public Goods findOne(@PathVariable("id") int id){
        //1.造个异常
        int i = 3/0;
        try {
        	//2. 休眠2秒
        	Thread.sleep(2000);
        } catch (InterruptedException e) {
        	e.printStackTrace();
        }
        Goods goods = goodsService.findOne(id);
        goods.setTitle(goods.getTitle() + ":" + port);//将端口号,设置到了 商品标题上
        return goods;
    }
    
  4. 在启动类上开启Hystrix功能:@EnableCircuitBreaker

    package com.itest.provider;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    
    @EnableEurekaClient //该注解 在新版本中可以省略
    @SpringBootApplication
    
    @EnableCircuitBreaker // 开启Hystrix功能
    
    public class ProviderApp {
        public static void main(String[] args) {
            SpringApplication.run(ProviderApp.class,args);
        }
    }
    
2.Hystrix-降级-消费方降级

消费方

  1. feign 组件已经集成了 hystrix 组件。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1JLnYIh8-1594119654957)(assets/image-20200627215616768.png)]

  1. 定义feign 调用接口实现类,复写方法,即 降级方法

    package com.ittest.consumer.feign;
    import com.ittest.consumer.domain.Goods;
    import org.springframework.stereotype.Component;
    /**
     * Feign 客户端的降级处理类
     * 1. 定义类 实现 Feign 客户端接口
     * 2. 使用@Component注解将该类的Bean加入SpringIOC容器
     */
    @Component
    public class GoodsFeignClientFallback implements GoodsFeignClient {
        @Override
        public Goods findGoodsById(int id) {
            Goods goods = new Goods();
            goods.setTitle("又被降级了~~~");
            return goods;
        }
    }
    
  2. 在 @FeignClient 注解中使用 fallback 属性设置降级处理类。

    package com.ittest.consumer.feign;
    
    import com.ittest.consumer.domain.Goods;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    
    @FeignClient(value = "HYSTRIX-PROVIDER",fallback = GoodsFeignClientFallback.class)
    public interface GoodsFeignClient {
        @GetMapping("/goods/findOne/{id}")
        public Goods findGoodsById(@PathVariable("id") int id);
    }
    
  3. 配置开启 feign.hystrix.enabled = true

    server:
      port: 9000
    eureka:
      instance:
        hostname: localhost # 主机名
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka
    spring:
      application:
        name: hystrix-consumer # 设置当前应用的名称。将来会在eureka中Application显示。将来需要使用该名称来获取路径
    
    # 开启feign对hystrix的支持
    feign:
      hystrix:
        enabled: true
    

在这里插入图片描述

什么时候会触发feign降级?

  • 超时,服务端报错
3.Hystrix-熔断-概念

在这里插入图片描述

参考例子:自恢复保险丝 https://www.jianshu.com/p/eb093106e503

4.Hystrix-熔断-代码演示

默认是5秒内请求次数最少不低于20次,失败比例的阈值是50%,熔断器打开

http://localhost:9000/order/goods/1

  • 当等于1时,做 除0 崩溃

http://localhost:9000/order/goods/2

  • 正常

打开f12 按f5强制刷新测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值