温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringCloud-Hystrix实现原理是什么

发布时间:2021-05-31 14:20:06 来源:亿速云 阅读:185 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关SpringCloud-Hystrix实现原理是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

一、思维导图

SpringCloud-Hystrix实现原理是什么

二、Hystrix包含的内容

(1) 服务降级

1)什么是服务降级

有了服务的熔断,随之就会有服务的降级,所谓服务降级,就是当某个服务熔断之后,服务端提供的服务将不再被调用,此时由客户端自己准备一个本地的fallback回调,返回一个默认值来代表服务端的返回;

这种做法,虽然不能得到正确的返回结果,但至少保证了服务的可用,比直接抛出错误或者服务不可用要好很多。

2)如何进行服务降级

(1)服务端

1、POM

 <dependencies>
        <!--hystrix-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>com.tfjy.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2、YML

server:
  port: 8001
 
spring:
  application:
    name: cloud-provider-hystrix-payment
 
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      #defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
      defaultZone: http://localhost:7001/eureka/

3、主启动

需要在主启动上加上

SpringCloud-Hystrix实现原理是什么

4、业务类

controller

 @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id){
        String result = paymentService.paymentInfo_TimeOut(id);
        log.info("*****result"+result);
        return result;
    }

service

 @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="5000")
    })
    public String paymentInfo_TimeOut(Integer id){
       try{
           TimeUnit.SECONDS.sleep(5);
        }catch (InterruptedException e){
           e.printStackTrace();
        }
        return "线程池:"+Thread.currentThread().getName()+"paymentInfo_TimeOut,id"+id+"O(∩_∩)O哈哈~"+"耗时5秒钟";
    }
 
    public String paymentInfo_TimeOutHandler(Integer id){
        return "线程池:"+Thread.currentThread().getName()+"paymentInfo_TimeOutHandler,id"+id+"o(╥﹏╥)o";
    }

在代码上加上HystrixCommand注解,然后由个属性fallbackMethod,value值可以填写方法的名字。

当发生超时的时候,就会走下面的方法。

SpringCloud-Hystrix实现原理是什么

1、POM

<dependencies>
    <!--openfeign-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <!--hystrix-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    <!--eureka client-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
    <dependency>
        <groupId>com.tfjy.springcloud</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <!--web-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--一般基础通用配置-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

2、YML

server:
  port: 80
 
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:7001/eureka/
 
feign:
  hystrix:
    enabled: true

3、主启动

SpringCloud-Hystrix实现原理是什么

4、业务

@GetMapping("/consumer/payment/hystrix/timeout/{id}")
    @HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")
    })
//    @HystrixCommand
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id)
    {
        int age = 10/0;
        String result = paymentHystrixService.paymentInfo_TimeOut(id);
        return result;
    }
    public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id)
    {
        return "我是消费者80,对方支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
    }
@Component
@FeignClient(value = "CLOUD-PROVIDER-HYSTRIX-PAYMENT",fallback = PaymentFallbackService.class)
public interface PaymentHystrixService {
 
    @GetMapping("/payment/hystrix/ok/{id}")
    public   String paymentInfo_ok(@PathVariable("id") Integer id);
 
    @GetMapping("/payment/hystrix/timeout/{id}")
    public   String paymentInfo_TimeOut(@PathVariable("id") Integer id);
}

这个参数要一样

这个只能等待1.5s但是在8001要5s

SpringCloud-Hystrix实现原理是什么

三、全局配置

@RestController
@Slf4j
@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")
public class OrderHystirxController {
   @GetMapping("/consumer/payment/hystrix/timeout/{id}")
//    @HystrixCommand(fallbackMethod = "paymentTimeOutFallbackMethod",commandProperties = {
//            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1500")
//    })
    @HystrixCommand
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id)
    {
        int age = 10/0;
        String result = paymentHystrixService.paymentInfo_TimeOut(id);
        return result;
    }
    public String paymentTimeOutFallbackMethod(@PathVariable("id") Integer id)
    {
        return "我是消费者80,对方支付系统繁忙请10秒钟后再试或者自己运行出错请检查自己,o(╥﹏╥)o";
    }
 
    // 下面是全局fallback方法
    public String payment_Global_FallbackMethod()
    {
        return "Global异常处理信息,请稍后再试,/(ㄒoㄒ)/~~";
    }
}

@DefaultProperties(defaultFallback = "payment_Global_FallbackMethod")

1:1 每个方法配置一个服务降级方法,技术上可以,实际上傻X

1:N 除了个别重要核心业务有专属,其它普通的可以通过@DefaultProperties(defaultFallback = "") 统一跳转到统一处理结果页面

通用和独享的各自分开,避免了代码膨胀,合理减少了代码量

SpringCloud-Hystrix实现原理是什么

三、哪些情况会发生服务降级

(1) 程序运行异常 (当我们把service方法中改成int i =10/0)

(2) 超时

(3) 服务熔断触发服务降级

(4) 线程池/信号量也会导致服务降级

(2) 服务熔断

一、概念

(1)什么是服务熔断

熔断这一概念来源于电子工程中的断路器(Circuit Breaker)。在互联网系统中,当下游服务因访问压力过大而响应变慢或失败,上游服务为了保护系统整体的可用性,可以暂时切断对下游服务的调用。

在固定时间窗口内,接口调用超时比率达到一个阈值,会开启熔断。进入熔断状态后,后续对该服务接口的调用不再经过网络,直接执行本地的默认方法,达到服务降级的效果。

熔断不可能是永久的。当经过了规定时间之后,服务将从熔断状态回复过来,再次接受调用方的远程调用。

(2)熔断的三种状态

SpringCloud-Hystrix实现原理是什么

  • 熔断关闭状态(Closed) 服务没有故障时,熔断器所处的状态,对调用方的调用不做任何限制。

  • 熔断开启状态(Open) 在固定时间窗口内(Hystrix默认是10秒),接口调用出错比率达到一个阈值(Hystrix默认为50),会进入熔断开启状态,进入熔断状态后,后续对该服务接口的调用不再经过网络,直接执行本地的fallback方法。

  • 半熔断状态(half-open)哎进入熔断开启状态一段时间之后(Hystrix默认是5秒),熔断器会进入半熔断状态,所谓半熔断就是尝试恢复服务调用,允许有限的流量调用该服务,并监控调用成功率,如果成功率达到了预期,则说明服务已恢复,进入熔断关闭状态;如果成功率仍旧很低,则重新进入熔断关闭状态。

二、配置熔断

(2)pom

<dependencies>
        <!--hystrix-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

(2)YML

server:
  port: 8001
 
spring:
  application:
    name: cloud-provider-hystrix-payment
 
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      #defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
      defaultZone: http://eureka7001.com:7001/eureka

(3)主启动

@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001
{
    public static void main(String[] args) {
            SpringApplication.run(PaymentHystrixMain8001.class, args);
    }
}

(4)业务

 //====服务熔断
    @GetMapping("/payment/circuit/{id}")
    public String paymentCircuitBreaker(@PathVariable("id") Integer id)
    {
        String result = paymentService.paymentCircuitBreaker(id);
        log.info("****result: "+result);
        return result;
    }
 //=====服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id)
    {
        if(id < 0)
        {
            throw new RuntimeException("******id 不能负数");
        }
        String serialNumber = IdUtil.simpleUUID();
 
        return Thread.currentThread().getName()+"\t"+"调用成功,流水号: " + serialNumber;
    }
    public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id)
    {
        return "id 不能负数,请稍后再试,/(ㄒoㄒ)/~~   id: " +id;
    }

涉及到断路器的三个重要参数:快照时间窗、请求总数阈值、错误百分比阈值

1:快照时间窗: 断路器确定是否打开需要统计一些请求和错误数据,而统计的时间范围就是快照时间窗,默认为最近的10秒。

2: 请求总数阈值: 在快照时间窗内,必须满足请求总数阈值才有资格熔断。默认为20,意味着在10秒内,如果该hystrix命令的调用次数不足20次,即使所有的请求都超时或其他原因失败,断路器都不会打开。

3: 错误百分比阈值:当请求总数在快照时间窗口内超过了阈值,比如发生了30次调用,如果在这30次调用中,有15次发生了超时异常,也就是超过50%的错误百分比,在默认设定50%阈值情况下,这时候就会将断路器打开。

(3) 服务限流

1、限流概念

Hystrix把一个分布式系统的某一个服务打造成一个高可用的服务最重要的手段之一就是资源隔离,即通过限流来限制对某一服务的访问量,比如说对Mysql的访问,为了避免过大的流量直接请求mysql服务,hstrix通过线程池或者信号量技术进行限流访问。

我们了解到Hystrix的两种隔离技术:线程池和信号量。线程池和信号量,也分析了在什么样的场景下使用线程池和信号量,通常来说线程池资源隔离技术一般用于对依赖服务的网络请求访问,需要解决timeout问题。信号量则适合对内部的一些比较复杂的业务逻辑访问,不涉及任何的网络请求,当并发量超过计数器指定值时,直接拒绝。

线程池隔离的最大优点在于:任何一个依赖服务都可以被隔离在自己的线程池内,即使自己的线程池资源填满了,也不会影响任何其他的服务调用。最大缺点在于:增加了cpu的开销,除了tomcat本身的调用线程之外,还有hystrix自己管理的线程池。每个command的执行都依托一个独立的线程,会进行排队,调度,还有上下文切换。

2、资源隔离

(1)线程隔离

Service

//------------------线程隔离
    //groupKey 一组command ,如果没有配这个,相同的groupkey会使用同一个线程池
    @HystrixCommand(groupKey = "thread1-group",commandKey = "thread1",threadPoolKey = "thread1",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "30000")
    },threadPoolProperties = {
            @HystrixProperty(name = "coreSize",value = "3"),
            @HystrixProperty(name = "maxQueueSize",value = "5")
    })
    public void thread1(){
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            System.out.println(111);
        }
        System.out.println(Thread.currentThread().getName());
    }

controller

 @GetMapping("getThread")
    public void getThread(){
        System.out.println(Thread.currentThread().getName());
        paymentService.thread1();
    }

当请求getThread的时候

http-nio-8001-exec-1
hystrix-thread1-1
http-nio-8001-exec-3
hystrix-thread1-2

会发现两个线程池是不一样的。

我现在在service中再添加一个

 //------------------线程隔离
    //groupKey 一组command ,如果没有配这个,相同的groupkey会使用同一个线程池
    @HystrixCommand(groupKey = "thread1-group",commandKey = "thread1",threadPoolKey = "thread1",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "3000")
    },threadPoolProperties = {
            @HystrixProperty(name = "coreSize",value = "3"),
            @HystrixProperty(name = "maxQueueSize",value = "5")
    })
    public void thread1(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            System.out.println(111);
        }
        System.out.println(Thread.currentThread().getName());
    }
    @HystrixCommand(groupKey = "thread2-group",commandKey = "thread2",threadPoolKey = "thread2",threadPoolProperties = {
            @HystrixProperty(name = "coreSize",value = "3"),
            @HystrixProperty(name = "maxQueueSize",value = "5"),
    },commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "1000")})
    public void thread2(){
        System.out.println(111);
        System.out.println(Thread.currentThread().getName());
    }

在controller中调用

 @GetMapping("getThread")
    public void getThread(){
        System.out.println(Thread.currentThread().getName());
        paymentService.thread1();
        paymentService.thread2();
    }
http-nio-8001-exec-1
hystrix-thread1-1
111
hystrix-thread2-1
@HystrixProperty(name = "coreSize",value = "3"), ## 这个表示核心线程数
@HystrixProperty(name = "maxQueueSize",value = "5"), ## 这个表示这个队列中的线程数为5个
所以这里面有8个

ps:下面看下对SpringCloud Hystrix的使用个人总结

和一般的开箱即用工具类似,SpringCloud Hystrix只需要最多四步即可基本使用上

1. 引入依赖:   spring-cloud-starter-hystrix

2. 添加支持:   在启动类上添加@EnableHystrix

3. 具体使用:   在有熔断需求的服务接口实现上标注@HystrixCommand,指定发生熔断时的回调方法

4. 按需配置:   比如配置熔断时间

需要注意的是在具体使用环节:

1. 回调方法必须在声明@HystrixCommand的方法所在的类中,即回调方法必须是服务接口的兄弟方法

2. 回调方法的参数列表必须和服务接口的参数列表完全一致,否则报找不到回调方法异常.

回调方法保持与原接口参数列表强一致,说明回调方法就是原接口的替补接口,备胎接口.

通过对Hystrix的使用总结,再次验证了开箱即用工具的使用套路.

1.引入依赖

2.添加支持

3.具体使用

4.按需配置

感谢各位的阅读!关于“SpringCloud-Hystrix实现原理是什么”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI