spring cloud 之 Hystrix

这篇具有很好参考价值的文章主要介绍了spring cloud 之 Hystrix。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Hystrix概述

Hystrix是一个供分布式系统使用,提供延迟和容错功能,保证复杂的分布系统在面临不可避免的失败是时,仍具有弹性。

当服务器A调用服务器B时,如果服务器B宕机,则服务器A不去调用。当服务器B在时间范围内未响应,服务器A延迟时间等待服务器B的响应,在SpringCloud框架里熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是5秒内20次调用失败就会启动熔断机制

Hystrix的概念

服务熔断的状态

Closed:关闭状态,所有请求都正常访问。

Open:打开状态,所有请求都会被降级。Hystix会对请求情况计数,当一定时间内失败请求百分比达到阈值,则触发熔断,断路器会完全打开。默认失败比例的阈值是50%,请求次数最少不低于20次。

Half Open:半开状态,open状态不是永久的,打开后会进入休眠时间(默认是5S)。随后断路器会自动进入半开状态。此时会释放部分请求通过,若这些请求都是健康的,则会完全关闭断路器,否则继续保持打开,再次进行休眠计时

继承openFeign方式实现熔断

这里的注册中心选用Nacos,openFeign

服务调用方搭建

引入依赖

<dependencies>
        <!--nacos客户端依赖-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
         <!--feign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--  feign性能优化 apache httpclient包 支持连接池 默认使用jdk urlConnection 不支持连接池-->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

配置文件

spring:
  application:
    name: cloud-feign-client
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
server:
  port: 9300
feign:
  httpclient:
    connection-timeout: 5000
  hystrix:
    enabled: true
hystrix:
  command:
    default:
      circuitBreaker:
        # 触发熔断的错误比例
        errorThresholdPercentage: 50
        # 熔断后的休眠时间,单位:毫秒,即熔断开启到正常访问服务的时间间隔
        sleepWindowMilliseconds: 100000
        # 触发熔断的最小请求次数
        requestVolumeThreshold: 2
      execution:
        timeout:
          enabled: true
        isolation:
          # 隔离策略:线程隔离
          strategy: THREAD
          thread:
            # 线程超时时间:调用Fallback
            timeoutInMilliseconds: 5000

这里使用第一种方式实现熔断,集成openFeign的接口,也就是FeignFallback 

package com.slbuildenv.cloud.client;

import com.slbuildenv.cloud.hysrix.FeignFallback;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

@FeignClient(value="cloud-test-service" ,fallback = FeignFallback.class)
public interface TestFeign {

    @GetMapping("/find/date")
    String findDate();
}
package com.slbuildenv.cloud.hysrix;

import com.slbuildenv.cloud.client.TestFeign;
import org.springframework.stereotype.Component;

@Component
public class FeignFallback  implements TestFeign {

    @Override
    public String findDate() {
        System.out.println("服务熔断降级");
        return "服务熔断降级";
    }
}

 调用controller

package com.slbuildenv.cloud.controller;

import com.slbuildenv.cloud.client.TestFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/feign")
public class TestFeignRemote {

    @Autowired
    private TestFeign testFeign;

    @GetMapping("/date")
    public String getRemoteDate() throws InterruptedException {
       return  testFeign.findDate();
    }

}

被调用方搭建

配置文件就不列举啦,就是注册个nacos注册中心,依赖不需要Hystrix

package com.slbuildenv.cloud.controller;

import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/find")
@RefreshScope
public class TestFeign {


    @GetMapping("/date")
    public String getDate(){
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }
}

测试调用

不启动被调用方

spring cloud 之 Hystrix,springCloud,spring cloud,hystrix,java

注解方式实现熔断

启动类上加@EnableHystrix

package com.slbuildenv.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrix
public class FeignMainApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignMainApplication.class,args);
    }
}

 调用方法添加@HystrixCommand方法

package com.slbuildenv.cloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.slbuildenv.cloud.client.TestFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/feign")
public class TestFeignRemote {

    @Autowired
    private TestFeign testFeign;

    @GetMapping("/date")
    @HystrixCommand(fallbackMethod = "fallBack")
    public String getRemoteDate() throws InterruptedException {
       return  testFeign.findDate();
    }

    public String fallBack(){
        System.out.println("注解方式实现熔断");
        return "注解方式实现熔断";
    }
}

需要去掉继承接口的方式:

@FeignClient(value="cloud-test-service" ,fallback = FeignFallback.class)

改为:

@FeignClient(value="cloud-test-service")

如果不去掉,两者共存,则继承接口方式会覆盖注解方式实现,优先级较高

测试结果 

spring cloud 之 Hystrix,springCloud,spring cloud,hystrix,java文章来源地址https://www.toymoban.com/news/detail-564581.html

 其他注解配置

        // 当前隔离策略选择信号池隔离的时候,用来设置信号池的大小(最大并发数)
        @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests",value = "10"),

        // 配置命令执行的超时时间
        @HystrixProperty(name = "execution.isolation.thread.timeOutInMilliseconds",value = "10"),

        // 是否启用超时时间
        @HystrixProperty(name = "execution.timeout.enabled",value = "true"),

        // 执行超时的时候是否中断
        @HystrixProperty(name = "execution.isolation.thread.interruptOnTimeout",value = "true"),

        // 执行被取消的时候是否中断
        @HystrixProperty(name = "execution.isolation.thread.interruptOnCancel",value = "true"),

        // 允许回调方法执行的最大并发数
        @HystrixProperty(name = "fallback.isolation.semaphore.maxConcurrentRequests",value = "10"),

        // 服务降级是否启用,是否执行回调函数
        @HystrixProperty(name = "fallback.enabled",value = "true"),

        // 是否启用断路器
        @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),

        // 该属性用来设置在滚动时间窗中,断路器熔断的最小请求数。
        // 例如,默认该值为20的时候,如果滚动时间窗(默认10s)内仅收到了19个请求,即使这19个请求都失败了,断路器也不会打开。
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "20"),

        // 该属性用来设置在滚动时间窗中,表示在滚动时间窗中,在请求数量超过circuitBreaker.RequestVolumeThreshold的情况下,
        // 如果错误请求数的百分比超过50,就把断路器设置为“打开”状态,否则就设置为“关闭”状态。
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期

        // 断路器强制打开
        @HystrixProperty(name = "circuitBreaker.forceOpen",value = "false"),

        // 断路器强制关闭
        @HystrixProperty(name = "circuitBreaker.forceClosed",value = "false"),

        // 滚动时间窗设置,该时间用于断路器判断健康度时需要收集信息的持续时间
        @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "10000"),

        // 该属性用来设置滚动时间窗统计指标信息时划分“桶”的数量,
        // 断路器在收集指标信息的时候会根据设置的时间窗长度拆分成多个“桶”来累计个度量值,每个“桶”记录了一段时间内的采集指标。
        // 比如10s内拆分成10个“桶”收集指标,所以timeinMilliseconds必须能被numBuckets整除。否则会抛异常
        @HystrixProperty(name = "metrics.rollingStats.numBuckets",value = "10"),

        // 该属性用来设置对命令执行的延迟是否使用百分位数来跟踪和计算。如果设置为false,那么所有的概要统计都将返回-1.
        @HystrixProperty(name = "metrics.rollingPercentile.enabled",value = "false"),

        // 该属性用来设置百分位统计的滚动窗口的持续时间,单位为毫秒。
        @HystrixProperty(name = "metrics.rollingPercentile.timeInMilliseconds",value = "60000"),

        // 该属性用来设置百分位统计滚动窗口中使用“桶”的数量。
        @HystrixProperty(name = "metrics.rollingPercentile.numBuckets",value = "60000"),

        // 该属性用来设置在执行过程中每个“桶”中保留的最大执行次数。如果在滚动时间窗内发生超过该设定值的执行次数,就从最初的位置开始重写。
        // 例如,将该值设置为100,滚动窗口为10s,若在10s内一个“桶”中发生了500次执行,那么该“桶”中只保留最后的100次执行的统计。
        // 另外,增加该值的大小将会增加内存量的消耗,并增加排序百分位数所需的计算时间。
        @HystrixProperty(name = "metrics.rollingPercentile.bucketSize",value = "100"),

        // 该属性用来设置采集影响熔断器状态的健康快照(请求的成功、错误百分比)的间隔等待时间。
        @HystrixProperty(name = "metrics.healthSnapshot.intervalInMilliseconds",value = "500"),

        // 是否开启请求缓存
        @HystrixProperty(name = "requestCache.enabled",value = "true"),

        // HystrixCommand的执行和事件是否打印日志到HystrixRequestLog中
        @HystrixProperty(name = "requestLog.enabled",value = "true"),

        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
},threadPoolProperties = {

        // 该参数用来设置执行命令线程池的核心线程数,该值也就是命令执行的最大并发量
        @HystrixProperty(name = "coreSize",value = "10"),

        // 该参数用来设置线程池的最大队列大小。当设置为-1时,线程池将使用SynchronousQueue实现的队列,
        // 否则将使用LinkedBlockingQueue实现的队列
        @HystrixProperty(name = "maxQueueSize",value = "-1"),

        // 该参数用来为队列设置拒绝阈值。通过该参数,即使队列没有达到最大值也能拒绝请求。
        // 该参数主要是对LinkedBlockingQueue队列的补充,
        // 因为LinkedBlockingQueue队列不能动态修改它的对象大小,而通过该属性就可以调整拒绝请求的队列大小了。
        @HystrixProperty(name = "queueSizeRejectionThreshold",value = "5"),
})

到了这里,关于spring cloud 之 Hystrix的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 第十一章 : Spring Cloud Hystrix 实战运用

    第十一章 : Spring Cloud Hystrix 实战运用 前言 本章知识点:本章将系统全面地介绍Spring Cloud Hystrix的相关知识点,包括Hystrix、设计目标,以及Spring Cloud Hystrix的基础用法和实战技巧,同时演示了Hystrix Dashboard的监控集成以及Turbine聚合Hystrix的监控。 Hystrix是由Netflix开源的一个针对

    2024年01月16日
    浏览(7)
  • Spring Cloud 容错机试 Hystrix 服务降级 RestTemplate:

    Spring Cloud 容错机试 Hystrix 服务降级 RestTemplate:

    雪崩效应:   如果短信服务炸了后面的所有服务就会起连锁反应造成全部服务挂掉 , 这就是雪崩效应 , 那么其实短信服务又不是我们主要业务 , 这个时候我们可以采用服务降级 , 服务降级就是暂时的把短信服务停掉能用就返回不能用就返回个错误 , 但是它也不会影响

    2024年02月07日
    浏览(12)
  • Spring Boot 中的 Spring Cloud Hystrix 是什么,原理,如何使用

    Spring Boot 中的 Spring Cloud Hystrix 是什么,原理,如何使用

    在分布式系统中,服务之间的调用是不可避免的。但是,当一个服务调用另一个服务时,如果被调用的服务出现了故障或者延迟,那么调用者也会受到影响,甚至会导致整个系统的崩溃。为了解决这个问题,Netflix 提供了一种解决方案:Hystrix。 在 Spring Cloud 中,Hystrix 是一个

    2024年02月12日
    浏览(48)
  • 云原生微服务 Spring Cloud Hystrix 降级、熔断实战应用

    云原生微服务 Spring Cloud Hystrix 降级、熔断实战应用

    第一章 Java线程池技术应用 第二章 CountDownLatch和Semaphone的应用 第三章 Spring Cloud 简介 第四章 Spring Cloud Netflix 之 Eureka 第五章 Spring Cloud Netflix 之 Ribbon 第六章 Spring Cloud 之 OpenFeign 第七章 Spring Cloud 之 GateWay 第八章 Spring Cloud Netflix 之 Hystrix 多个微服务之间调用的时候,假如微服

    2024年02月08日
    浏览(16)
  • (一)Spring Cloud 直击微服务作用、架构应用、hystrix降级

    (一)Spring Cloud 直击微服务作用、架构应用、hystrix降级

    直击微服务作用     遇到了什么问题?         将单体架构拆分成微服务架构后,如果保证多个服务(项目)正常运行?     哪个技术可以解决这个问题?         微服务技术         服务治理: 服务管理,维护服务与服务之间的关系     这个技术如何使用?         netflix/网飞:

    2024年02月03日
    浏览(65)
  • Spring Cloud OpenFeign:基于Ribbon和Hystrix的声明式服务调用

    Spring Cloud OpenFeign:基于Ribbon和Hystrix的声明式服务调用

    💗wei_shuo的个人主页 💫wei_shuo的学习社区 🌐Hello World ! Spring Cloud OpenFeign是一个声明式的服务调用框架,基于Feign并整合了Ribbon和Hystrix;目标是简化分布式系统中编写服务间调用的代码,并提供一种更加优雅和便捷的方式来进行服务之间的通信 依赖导入 application.yml配置 启

    2024年02月05日
    浏览(14)
  • 高版本Spring Cloud中OpenFeign整合Hystrix熔断降级不生效的问题及解决方案

    高版本Spring Cloud中OpenFeign整合Hystrix熔断降级不生效的问题及解决方案

    本文将介绍在使用高版本Spring Cloud(2020.0.x及以后),由于取消了Hystrix的集成,导致OpenFeign与Hystrix熔断降级不生效的问题。同时,也将给出解决该问题的方案,即添加feign.circuitbreaker.enabled=true配置。 随着Spring Cloud框架的发展,高版本Spring Cloud(2020.0.x及以上)中取消了对Hy

    2024年02月22日
    浏览(47)
  • 1024程序员节特辑 | 解密Spring Cloud Hystrix熔断提高系统的可用性和容错能力

    1024程序员节特辑 | 解密Spring Cloud Hystrix熔断提高系统的可用性和容错能力

    专栏集锦,大佬们可以收藏以备不时之需 Spring Cloud实战专栏:https://blog.csdn.net/superdangbo/category_9270827.html Python 实战专栏:https://blog.csdn.net/superdangbo/category_9271194.html Logback 详解专栏:https://blog.csdn.net/superdangbo/category_9271502.html tensorflow专栏:https://blog.csdn.net/superdangbo/category_869

    2024年02月08日
    浏览(14)
  • Spring Cloud Feign实战来袭:工程中配置断路器Hystrix报错NoClassDefFoundError:HystrixCommandAspect解决方案

    Spring Cloud Feign实战来袭:工程中配置断路器Hystrix报错NoClassDefFoundError:HystrixCommandAspect解决方案

    在Spring Cloud Feign工程中配置断路器Hystrix的时候,pom.xml文件已经加入Hystrix相关的jar: Application.java: 可以看出来是找不到HystrixCommandAspec.java这个类,于是在github上找到这个源文件: https://github.com/dmgcodevil/Hystrix/blob/958ec5d7b4bb967be077a4c2bbcdc71e7a7f5248/hystrix-contrib/hystrix-javanica/src/mai

    2024年02月16日
    浏览(13)
  • SpringCloud——Hystrix详解

    SpringCloud——Hystrix详解

    目录 一、Hystrix介绍 1、分布式系统面临问题 2、Hystrix概念 3、Hystrix作用 (1)服务降级 (2)服务熔断 二、服务降级案例 1、搭建Eureka服务端 (1)创建maven工程 (2)导入依赖 (3)配置application.yml (4)创建主启动类 (5)启动Eureka注册中心 2、搭建服务提供者Provider80 (1)创

    2023年04月16日
    浏览(8)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包