spring cloud 学习(4) - hystrix 服务熔断处理

hystrix 是一个专用于服务熔断处理的开源项目,当依赖的服务方出现故障不可用时,hystrix有一个所谓的断路器,一但打开,就会直接拦截掉对故障服务的调用,从而防止故障进一步扩大(类似中电路中的跳闸,保护家用电器)。

使用步骤:(仍然在之前的示例代码上加以改造)

一、添加hystrix依赖

compile ‘org.springframework.cloud:spring-cloud-starter-hystrix‘

二、在需要熔断的方法上添加注解

package com.cnblogs.yjmyzz.spring.cloud.study.service.controller;

import com.cnblogs.yjmyzz.spring.cloud.study.dto.UserDTO;
import com.cnblogs.yjmyzz.spring.cloud.study.service.client.UserFeignClient;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
public class OrderController {

    @Autowired
    private UserFeignClient userFeignClient;

    private final Random rnd = new Random(System.currentTimeMillis());

    @GetMapping("/order/{userId}/{orderNo}")
    @HystrixCommand(fallbackMethod = "findOrderFallback", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
    })
    public String findOrder(@PathVariable Integer userId, @PathVariable String orderNo) throws InterruptedException {
        Thread.sleep(rnd.nextInt(2000));
        UserDTO user = userFeignClient.findUser(userId);
        if (user != null) {
            return user.getUserName() + " 的订单" + orderNo + " 找到啦!";
        }
        return "用户不存在!";
    }

    public String findOrderFallback(Integer userId, String orderNo) {
        return "订单查找失败!";
    }
}  

注意findOrder上添加的HystrixCommand注解,大概意思是,如果这个方法调用失败,会切换到备用方法findOrderFallback上,而且还设置了一个超时时间1000ms,即1秒。换句话说,如果findOrder方法没有在1s内返回结果,也算调用失败,同样会切换到备用方法findOrderFallback上。

注:为了方便演示,故意在findOrder上随机停了2秒内的一段时间,所以预期这个方法,应该会在偶尔超时,偶尔正常。

关于HystrixProperty的更多属性,可参考github上的官方文档:https://github.com/Netflix/Hystrix/wiki/Configuration 

三、main入口上启用hytrix熔断

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

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

启用后,访问http://localhost:8002/order/1/100 ,可以看到类似以下输出:

正常时,返回类似上图的输出,如果超时,将返回下图:

此外,spring-boot的acturator也提供了health端点来查看hystrix状态,查看http://localhost:8002/health

这个表示hystrix的断路器未打开,如果 http://localhost:8002/order/1/100 这个页面狂刷(默认要5秒内失败20次以上),或者干脆把service-provider停掉,这个状态会变成:

表明此时断路器是打开的。

四、hystrix监控

health端点只能看到断路器的整体状态,但是对于细节展示不够详细,默认情况下,只要启用了hystrix功能,还会暴露一个端点hystrix.stream

访问 http://localhost:8002/hystrix.stream 可以查看详细的数据

注:这个页面会实时不断输出新的内容(如果有的话),首次访问的话,如果看到一直转圈,但是没有任何内容,说明这时服务对应的方法没人调用,可以访问findOrder方法后,再来看这个页面。

显然,一堆密密麻麻的文字,没有人会喜欢看,spring-cloud早就想到这一点了,提供了一个hystrix-dashboard的功能,可以用图形化的界面来解读这些数据。

再起一个项目,名为hystrix-dashboard,build.gradle参考下面:

buildscript {
    repositories {
        maven {
            url "http://maven.aliyun.com/nexus/content/groups/public/"
        }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.4.RELEASE")
    }
}

apply plugin: ‘org.springframework.boot‘

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:Dalston.RELEASE"
    }
}

dependencies {
    compile ‘org.springframework.cloud:spring-cloud-starter-eureka‘
    compile ‘org.springframework.cloud:spring-cloud-starter-hystrix-dashboard‘
    compile ‘org.springframework.boot:spring-boot-starter-actuator‘
}

main函数如下:

package com.cnblogs.yjmyzz.spring.cloud.study.hystrix;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

/**
 * Created by yangjunming on 2017/6/30.
 */
@SpringBootApplication
@EnableHystrixDashboard
@EnableDiscoveryClient
public class HystrixDashboardApplication {
    public static void main(String[] args) {
        SpringApplication.run(HystrixDashboardApplication.class, args);
    }
}  

当然,这也是一个微服务,也可以注册到eureka上,参考下面的配置:

spring:
  application:
    name: hystrix-dashboard
server:
  port: 8035

eureka:
  instance:
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://yjmyzz:[email protected]:8100/eureka,http://yjmyzz:[email protected]:8200/eureka,http://yjmyzz:[email protected]:8300/eureka

启用成功后,访问http://localhost:8035/hystrix,会出现类似下面这个界面:

第1个输入框里,填写要监控的hystrix.steam地址,然后title这里起一个名字即可,然后点击monitor steam,就能看到图表:

这显然比纯文字友好多了。还有一个问题,如果有多个hystrix.stream地址同时监控,或者把多个地址的数据汇总起来,该怎么弄?github上有一个turbine ,就是专门为解决这个问题的,大家可以自行研究下。

最后,附上文中示例代码地址:https://github.com/yjmyzz/spring-cloud-demo

spring cloud 学习(4) - hystrix 服务熔断处理

时间: 2024-08-06 07:54:49

spring cloud 学习(4) - hystrix 服务熔断处理的相关文章

Spring Cloud 学习 (四) Hystrix & Hystrix Dashboard & Turbine

在复杂的分布式系统中,可能有几十个服务相互依赖,这些服务由于某些原因,例如机房的不可靠性.网络服务商的不可靠性等,导致某个服务不可用 . 如果系统不隔离该不可用的服务,可能会导致整个系统不可用.Hystrix 提供了熔断器功能,能够阻止分布式系统中出现联动故障.Hystrix 是通过隔离服务的访问点阻止联动故障的,并提供了故障的解决方案,从而提高了整个分布式系统的弹性. 使用 Hystrix 在 Ribbon 使用 Hystrix 添加依赖包 <dependency> <groupId&

Spring Cloud 学习——5.使用 feign 的 hystrix 支持

1.前言 hystrix 是一个微服务系统的断路器组件,上文介绍了 spring cloud 通过 netfix hystrix 提供对 hystrix 的支持.同时 spring cloud 也提供了 openfeign 的支持, 而 openfeign 本身就已经内置了 hystrix 支持.所以本文介绍一个使用 openfeign 内置 hystrix 的简单示例. 前文链接: Spring Cloud 学习——3.openfeign实现声明式服务调用 Spring Cloud 学习——4

(一)spring cloud互联网分布式微服务云平台规划分析--spring cloud平台整体规

导语 近期公司孵化了一个互联网产品,随着业务发展,产品运营后用户数据量(过亿).业务数据量(过100亿)较大,技术团队配合产品.运营快速定制化开发, 还要考虑产品涉及的资金安全.消息的及时性.业务的制动化处理,我们选择鸿鹄cloud分布式云架构平台作为公司产品核心企业架构. 产品平台规划 微服务注册中心(分布式集群部署).微服务配置中心(分布式集群部署).服务网关平台(分布式集群部署). 微服务监控平台.SSO单点登录平台(分布式集群部署).微服务相关组件(分布式集群部署).后台管理平台. 定时

java B2B2C Springcloud电子商城系统-Spring Cloud学习

SpringCloud是什么? 需要JAVA Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码 一零三八七七四六二六 Spring Cloud是一个微服务框架,相比Dubbo等RPC框架, Spring Cloud提供的全套的分布式系统解决方案. Spring Cloud对微服务基础框架Netflix的多个开源组件进行了封装,同时又实现了和云端平台以及和Spring Boot开发框架的集成. Spring Cloud为微服务架构开发涉及的配置管理,服务治理,熔断机制

Spring Cloud学习之-什么是Spring Cloud?

SpringCloud 什么是微服务? 要想学习微服务,首先需要知道什么是微服务?为什么会有微服务?相信看完架构的发展史读者就会明白 架构发展史 单体应用架构 如图所示:将所有的模块,所有内容(页面.Dao.Service.Controller)全部写入一个项目中,放在一个Tomcat容器中启动适用于小型项目 优点:开发速度快,可以利用代码生成工具快速的开发一个项目 缺点:不易扩展,代码耦合度高,且不容错(当某部分出错后整个服务就会停止运行) 垂直架构 既然原来单体架构中代码耦合度高,不利于维护

Spring Cloud 学习——6.zuul实现路由、负载均衡、安全验证

1.前言 在一个大微服务架构的系统中,可能存在着很多服务,如果将这些服务全部对外暴露,会带来很多问题.比如安全问题,有些核心服务直接对外暴露很容易被攻击:比如身份验证问题,有些接口服务是要求登录的,如果各种服务各自对外暴露,那么这些要求登录的请求第一个触达的服务模块都要向“用户服务模块”查询鉴权结果,这样既对“用户服务模块”造成额外压力,也增加了这些其它服务模块的开发成本,所以应该考虑将身份验证的事情交到网关模块中直接完成:比如运维难度和成本问题,如果每一种服务都各自对外暴露,那么整个系统就需要

《Spring Cloud与Docker微服务架构实战》配套代码

不才写了本使用Spring Cloud玩转微服务架构的书,书名是<Spring Cloud与Docker微服务架构实战> - 周立,已于2017-01-12交稿.不少朋友想先看看源码,现将代码放出. 本次放出的代码: 共计70+个DEMO 覆盖Eureka.Ribbon.Feign.Hystrix.Zuul.Spring Cloud Config.Spring Cloud Bus.Spring Cloud Sleuth.Docker.Docker Compose等. 1-11章代码地址: ht

Spring Cloud入门教程-Hystrix断路器实现容错和降级

简介 Spring cloud提供了Hystrix容错库用以在服务不可用时,对配置了断路器的方法实行降级策略,临时调用备用方法.这篇文章将创建一个产品微服务,注册到eureka服务注册中心,然后我们使用web客户端访问/products API来获取产品列表,当产品服务故障时,则调用本地备用方法,以降级但正常提供服务. 基础环境 JDK 1.8 Maven 3.3.9 IntelliJ 2018.1 Git 项目源码 Gitee码云 添加产品服务 在intelliJ中创建一个新的maven项目,

Spring Cloud学习--配置中心(Config)

Spring Cloud学习--配置中心(Config) 一 Spring Cloud Config简介 二 编写 Config Server 三 编写Config Client 四 使用refresh端点手动刷新配置 五 Spring Config Server与Eurelka配合使用 六 Config Server的高可用 一. Spring Cloud Config简介 微服务要实现集中管理微服务配置.不同环境不同配置.运行期间也可动态调整.配置修改后可以自动更新的需求,Spring Cl