`
y806839048
  • 浏览: 1106627 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

Hystrix——服务容错

阅读更多

1 Hystrix 简介

在微服务架构中,微服务之间通过网络进行通信,存在相互依赖,当其中一个服务不可用时,有可能会造成雪崩效应。要防止这样的情况,必须要有容错机制来保护服务。
Hystrix是Netflix开源的一个延迟和容错库,它主要实现了以下几点:

  • 包裹请求
    使用HystrixCommand(或HystrixObservableCommand)包裹对依赖的调用逻辑,每个命令在独立线程中执行。
  • 跳闸机制
    当某服务的错误率超过一定阈值时,Hystrix可以自动或手动跳闸,停止请求该服务一段时间。
  • 资源隔离
    Hystrix为每个依赖都维护了一个小型的线程池(或信号量),如果该线程池已满,发往该依赖的请求就被立即拒绝。
  • 监控
    Hystrix可以近乎实时地监控运行指标和配置的变化。
  • 回退机制
    当请求失败、超时、被拒绝,或者当断路器打开时,执行回退逻辑。
  • 自我修复
    当断路器打开一段时间后,会自动进入“半打开”状态,允许一个请求访问依赖的服务,如果该请求成功,则关闭断路器,否则继续保持打开状态。

  概要:

 

 

dubbo的服务调用是通过注入server类(消费方(相当于服务方的rest代理)---》服务提供方)(用rest的话是消费方---》消费方),springcloud的服务间的调用直接用feignclient

 

 

 

 

springcloud的设计思路就是1,开启功能,2,在需要用功能的地方加上标志性的注解

 

1,导入jar依赖

2,启动类开启功能-----启动该功能,有了默认配置,就可基于此配置修改,启动了该功能就会自动扫描有该功能的标志性的注解,进行拦截处理

 

3,需要用此功能的地方加应用注解,------应用功能注解标志地方,好拦截处理

 

 

请求断路器:

 

 容错的地方写在服务调用方,服务出错,或者调用线程数超出hystrix给每个熔断的线程数就调用容错方法

 

1.ribbon整合  (自己直接rest不用feignt发起)

 

    没有整合feignclient的情况下,发起请求用resttemplate   回退用 @HystrixCommand(fallbackMethod = "errorFallback")  方法回退

 

 

2,feignclient整合,直接用(无需使用rest)

无需注解@EnableCircuitBreaker

开启feign:

  hystrix:

    enabled: true

 

   feignclient直接整合了restemplate,调用接口直接转化成rest --url请求  回退用@FeignClient(name = "eureka-client-demo", fallback = ErrorFallback.class)或者

   @FeignClient(name = "eureka-client-demo", fallbackFactory = ErrorFallbackFactory.class)   基于类,回退类中的同名方法回退

 

 

@FeignClient(name = "eureka-client-demo", configuration = DisableHystrix.class)---可禁用某一个feign的回退

 

请求熔断监控:

 

A:需要有监控其访问服务的时候feignclient的情况下要加 @EnableCircuitBreaker@EnableDiscoveryClient 之后经由其请求的服务都会监控到

 

  @EnableHystrixDashboard(可视化) 这个可视化监控可以另起一个项目--只是展现A监控的结果    ------这种方式只能监控单个服务(当前服务)的所有请求,响应数据

      在仪表盘输入监控数据的地址

 

 

B:监控多个服务的请求响应

   

   开启多监控

   @EnableTurbine

 

指定要监控的集群,机器

turbine:

  app-config: feign-demo,ribbon-demo

  cluster-name-expression: "'default'"

  combine-host-port: true

 

 

2 整合Hystrix

2.1 Ribbon整合Hystrix

1.添加相应的依赖:

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

2.在启动类里添加@EnableCircuitBreaker 或者 @EnableHystrix注解

@EnableCircuitBreaker
@EnableDiscoveryClient
@SpringBootApplication
public class RibbonDemoApplication {

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



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

3.为需要容错的方法添加@HystrixCommand注解,并使用fallbackMethod属性指定回退方法

    @HystrixCommand(fallbackMethod = "errorFallback")
    @GetMapping("/hello")
    public String hello() {

        return this.restTemplate.getForObject("http://eureka-client-demo/hello", String.class);
    }


    public String errorFallback() {
        return "Error!";
    }

@HystrixCommand的配置类似下面:

@HystrixCommand(fallbackMethod = "stubMyService",
    commandProperties = {
      @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE")
    }
)

2.2 Feign使用Hystrix

1.Spring Cloud 中,Feign默认已经整合了Hystrix,所以只需要在配置中启用Hystrix就会包裹全部Feign Client中的方法:

feign:
  hystrix:
    enabled: true

2.编写回退方法,编写一个Feign Client的实现类,在@FeignClient的fallback属性指定对应的类:

@FeignClient(name = "eureka-client-demo", fallback = ErrorFallback.class)
public interface DemoFeignClient {

    @GetMapping("/hello")
    public String hello();
}


@Component
public class ErrorFallback implements DemoFeignClient {

    @Override
    public String hello() {
        return "Error!";
    }
}

3.如果需要回退方法打印错误信息,可以使用fallbackFactory(fallback和fallbackFactory只能使用其中一种):

@FeignClient(name = "eureka-client-demo", fallbackFactory = ErrorFallbackFactory.class)
public interface DemoFeignClient {

    @GetMapping("/hello")
    public String hello();
}


@Component
public class ErrorFallbackFactory implements FallbackFactory<DemoFeignClient> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ErrorFallbackFactory.class);

    @Override
    public DemoFeignClient create(Throwable throwable) {
        return new DemoFeignClient() {
            @Override
            public String hello() {
                //如果在create()中打印错误信息的话,在应用程序启动时就会打印
                ErrorFallbackFactory.LOGGER.info("fall back cause: ", throwable);
                return "Error!";
            }
        };
    }
}

4.如果不想某个Feign Client使用Hystrix的话,可以使用如下配置:

@FeignClient(name = "eureka-client-demo", configuration = DisableHystrix.class)
public interface DemoFeignClient {

    @GetMapping("/hello")
    public String hello();
}

@Configuration
public class DisableHystrix {

    @Bean
    @Scope("prototype")
    public Feign.Builder feignBuilder() {
        return Feign.builder();
    }
}

3 Hystrix监控

3.1 Ribbon中Hystrix的监控

Hystrix提供了端点/hystrix.stream用于监控Hystrix的情况,Ribbon在整合了Hystrix之后,还需要引入Spring Boot 的actuator依赖,才能通过/hystrix.stream监控接口运行情况。

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

/hystrix.stream的页面会返回类似下面的监控数据:

data: {"type":"HystrixCommand","name":"hello","group":"Controller","currentTime":1516202320578,"isCircuitBreakerOpen":false,"errorPercentage":100,"errorCount":1,"requestCount":1,"rollingCountBadRequests":0,"rollingCountCollapsedRequests":0,"rollingCountEmit":0,"rollingCountExceptionsThrown":0,"rollingCountFailure":1,"rollingCountFallbackEmit":0,"rollingCountFallbackFailure":0,"rollingCountFallbackMissing":0,"rollingCountFallbackRejection":0,"rollingCountFallbackSuccess":1,"rollingCountResponsesFromCache":0,"rollingCountSemaphoreRejected":0,"rollingCountShortCircuited":0,"rollingCountSuccess":0,"rollingCountThreadPoolRejected":0,"rollingCountTimeout":0,"currentConcurrentExecutionCount":0,"rollingMaxConcurrentExecutionCount":0,"latencyExecute_mean":0,"latencyExecute":{"0":0,"25":0,"50":0,"75":0,"90":0,"95":0,"99":0,"99.5":0,"100":0},"latencyTotal_mean":0,"latencyTotal":{"0":0,"25":0,"50":0,"75":0,"90":0,"95":0,"99":0,"99.5":0,"100":0},"propertyValue_circuitBreakerRequestVolumeThreshold":20,"propertyValue_circuitBreakerSleepWindowInMilliseconds":5000,"propertyValue_circuitBreakerErrorThresholdPercentage":50,"propertyValue_circuitBreakerForceOpen":false,"propertyValue_circuitBreakerForceClosed":false,"propertyValue_circuitBreakerEnabled":true,"propertyValue_executionIsolationStrategy":"THREAD","propertyValue_executionIsolationThreadTimeoutInMilliseconds":1000,"propertyValue_executionTimeoutInMilliseconds":1000,"propertyValue_executionIsolationThreadInterruptOnTimeout":true,"propertyValue_executionIsolationThreadPoolKeyOverride":null,"propertyValue_executionIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests":10,"propertyValue_metricsRollingStatisticalWindowInMilliseconds":10000,"propertyValue_requestCacheEnabled":true,"propertyValue_requestLogEnabled":true,"reportingHosts":1,"threadPool":"Controller"}

3.2 Feign中Hystrix的监控

1.虽然Feign整合了Hystrix,但是并没有整合到监控的模块,所以我们需要重新引入依赖包:

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

2.在启动类添加@EnableCircuitBreaker或者@EnableHystrix注解

@EnableCircuitBreaker
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class FeignDemoApplication {

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

然后就可以通过端点/hystrix.stream查看监控数据。

4 可视化监控

4.1 监控单个服务

可以使用hystrix-dashboard进行可视化监控:
1.创建一个新项目,并引入以下依赖:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
        </dependency>
  1. 在启动类加上@EnableHystrixDashboard注解
@EnableHystrixDashboard
@SpringBootApplication
public class HystrixDashboardApplication {

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

3.启动应用,打开/hystrix/端点,可以看到一下页面:

 
hystix-dashboard.PNG

往url栏输入/hystrix.stream的链接,如:http://localhost:8004/hystrix.stream,再点击Monitor Stream按钮,就可以看到如下图的页面:
 
hystix-dashboard-detail.PNG

 

4.2 监控多个服务

上面的方法只能监控单个服务,如果要监控多个服务,可以使用turbine,然后再使用hystrix-dashboard进行进行可视化监控。
1.新建一个项目,引入turbine的依赖

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

2.在启动类添加@EnableTurbine注解

@EnableTurbine
@SpringBootApplication
public class TurbineApplication {

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

3.配置文件:

server:
  port: 8006
spring:
  application:
    name: turbine
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8001/eureka/
  instance:
    prefer-ip-address: true

turbine:
  app-config: feign-demo,ribbon-demo
  cluster-name-expression: "'default'"
  combine-host-port: true
  • app-config 指定需要监控的服务,用逗号分隔
  • cluster-name-expression 指定集群名称
  • combine-host-port 按主机名和端口区分服务,turbine默认相同host的为同一服务,将该属性设为true后就可以按主机名和端口区分服务

4.启动应用,打开/turbine.stream端点即可以看到两者的监控数据。这个时候,再将turbine的监控数据接入hystrix-dashboard,比如,将url地址http://localhost:8006/turbine.stream填入dash-board的url一栏,再点击Monitor Stream按钮,就可以同时看到两个服务的监控数据。

4.3 使用消息中间件收集数据(RabbitMQ)

  1. 提供服务的微服务添加以下依赖:(这种才需要在提供服务的地方也加依赖
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-hystrix-stream</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
        </dependency>
  1. 添加RabbitMQ的配置:
spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
  1. Turbine项目移除turbine的依赖并添加以下依赖:
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-turbine-stream</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
        </dependency>
  1. 启动类中@EnableTurbine修改为@EnableTurbineStream
  2. 添加RabbitMQ的配置,同2,同时去掉turbine的配置。

参考:

https://blog.csdn.net/forezp/article/details/69934399

https://www.jianshu.com/p/8e577d8c1b20

 

 

 

分享到:
评论

相关推荐

    hystrix-dashboar1.5.12

    Hystrix 是一个用于处理分布式系统中延迟和故障的库,通过断路器模式来隔离服务间的调用,防止服务雪崩,提高系统的容错性。而Hystrix Dashboard 提供了可视化界面,帮助开发者实时监控这些断路器的状态,了解服务的...

    Hystrix.zip

    然而,随着服务数量的增加,服务间的依赖关系也变得复杂,这就引入了一个新的挑战——服务容错。Netflix的开源项目Hystrix就是为了解决这个问题而诞生的,它被誉为构建弹性微服务的关键技术。 Hystrix的核心概念是...

    srpingcloudEurekaRibbonHystrix.zip

    三、Hystrix——容错管理工具 Hystrix是Netflix开源的断路器库,其主要目标是防止服务雪崩,提高系统的健壮性。在微服务架构中,如果一个服务因故无法响应,可能会导致依赖它的其他服务也相继失败,进而引发整个...

    SpringCloud——断路器(Hystrix)

    在分布式系统中,Spring Cloud Hystrix 是一个关键的组件,它作为一个断路器来防止服务雪崩。断路器模式是微服务架构中的一个重要概念,用于提高系统的容错性和稳定性。下面我们将深入探讨 Spring Cloud Hystrix 的...

    Dubbo和Spring Cloud微服务架构对比——服务注册和发现.docx

    - **服务管理**:Spring Cloud提供了丰富的服务治理工具,如Hystrix(用于实现熔断、降级等)和Zuul(用于路由和服务网关)。 #### 总结 通过上述对比分析可以看出,Dubbo和Spring Cloud在服务注册与发现方面各有...

    构建微服务云原生应用——服务开发框架设计和实践.zip

    本主题围绕“构建微服务云原生应用——服务开发框架设计和实践”展开,旨在深入探讨微服务架构的设计原则和实践经验。 首先,我们需要理解微服务的核心概念。微服务强调单一职责原则,每个服务专注于一个特定业务...

    Hystrix 熔断、降级实例

    为了解决这个问题,Netflix开源了Hystrix,一个用于处理服务间调用失败、延迟和过载的库,通过隔离请求、熔断和降级策略,提高了系统的容错性和稳定性。本文将深入探讨Hystrix的核心功能——熔断和降级,并结合实际...

    Hystrix学习讲义大全.pdf

    在分布式系统设计中,服务之间的调用是常态,而Hystrix作为一个强大的工具,旨在解决这类系统中的关键问题——服务雪崩。服务雪崩是指由于某个服务的故障导致连锁反应,使得整个系统性能下降甚至瘫痪。其本质是线程...

    SpringCloud10-Hystrix熔断器学习代码及指定默认的全局兜底方法

    这个标题"SpringCloud10-Hystrix熔断器学习代码及指定默认的全局兜底方法"揭示了我们要讨论的主题——如何使用Hystrix进行熔断操作,并配置全局的 fallback 方法来处理服务调用失败的情况。 Hystrix的工作原理基于...

    spring-cloud-hystrix-feign(注册中心、member、feign-order).zip

    Hystrix是一个容错管理工具,旨在阻止服务雪崩效应,通过隔离服务调用、超时控制、断路器模式等机制来提高系统的健壮性。在Order服务中,当我们使用Feign调用Member服务时,Hystrix会在背后提供保护。当Member服务...

    SpringCloud——服务的注册与发现Eureka

    3. 集群模式:Eureka Server可以部署成集群,提高服务注册中心的可用性和容错性。 六、Eureka的配置优化 1. 配置服务实例的元数据,如版本号、环境等,便于服务治理。 2. 调整Eureka Server的心跳间隔、过期时间等...

    【微服务架构】SpringCloud之断路器(hystrix)

    本篇文章将聚焦于Spring Cloud中的断路器组件——Hystrix,它是Netflix开源的一款用于实现容错管理的工具。 断路器模式是一种设计模式,旨在防止应用程序因依赖故障而崩溃。在微服务架构中,服务之间通常通过网络...

    Spring Cloud Hystrix

    Hystrix 提供了一个强大的监控工具——Hystrix Dashboard,用于实时展示服务的运行状况和断路器的状态。通过 Hystrix Metrics Stream,我们可以将服务的指标暴露出来,以便于监控和诊断。此外,Turbine 可以聚合多个...

    httpd-2.4.43-lre312-x64-vc14.zip

    Apache HTTP服务器在这个场景下被用作一个测试工具,可能配合了Hystrix——一个由Netflix开发的库,用于处理服务之间的延迟和容错。Hystrix通过断路器模式来保护服务,防止雪崩效应,并提供了实时监控仪表盘,展示...

    hystrix-samples:我的hystrix示例代码的某个地方

    为了更好地理解Hystrix的工作原理,我们可以利用Hystrix提供的监控工具——Hystrix Dashboard。这个可视化界面可以实时展示命令和Collapser的执行情况,包括成功率、失败率、超时率等关键指标,帮助开发者及时发现并...

    Spring Cloud eureka服务注册DEMO

    在Eureka的架构中,集成Hystrix能增强系统的容错性和稳定性。 通过这个DEMO,我们可以学习到如何在Spring Cloud环境中设置Eureka服务注册和发现,以及如何在服务提供者和消费者之间进行通信。理解并掌握这些知识,...

    hystrix-parent:博客中Hystrix的示例源码工程

    《Hystrix:系统开源中的容错神器》 在当今的微服务架构中,系统间的交互变得日益频繁,为了保证系统的稳定性和高可用性,容错管理成为了必不可少的一部分。Netflix的Hystrix就是一个专为此设计的开源库,它提供了...

    java面试——SpringCloud面试专题.zip

    4. **Hystrix断路器**:Hystrix是Netflix开源的容错库,用于防止服务雪崩效应,通过隔离请求、降级策略、熔断机制,确保系统在高并发或者服务不可用时仍能保持稳定。 5. **Spring Cloud Config配置中心**:它允许...

    Spring Cloud简明教程

    Hystrix是一个延迟和容错库,旨在隔离访问远程系统、服务和第三方库,防止级联失败,提供回退机制。Hystrix通过断路器模式实现容错,它会在一定条件下打开断路器,阻止故障的发生和扩散。Hystrix还支持线程隔离和...

    springcloud1_springcloud技术框架_Eureka!_

    6. **服务降级和熔断**:Eureka通常与Hystrix结合使用,Hystrix提供服务降级、熔断和隔离机制,避免服务间的连锁故障,提高系统的容错性。例如,当某个服务调用失败或响应过慢时,Hystrix可以执行预设的降级策略,如...

Global site tag (gtag.js) - Google Analytics