学习SpringCloud之断路器Hystrix

简介

  • 什么是断路器?
    断路器就是为了解决微服务架构中的“雪崩”现象,即某个服务出现问题会导致其他服务阻塞,严重最终会导致服务器瘫痪。
    当服务出现问题是,断路器会负责断开这个该服务的依赖,以防止问题蔓延,保护整体服务。

  • Hystrix也是SpringCloudNetflix微服务套件中的一个组件,作为断路器的角色。

image

以下示例均基于SpringCloud的Greenwich.SR1版本。

基础依赖

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

Hystrix

@EnableHystrix 修饰启动一个SpringBoot应用。

@SpringBootApplication
@EnableHystrix
class HystrixClientStarter

fun main(args: Array<String>) {
    runApplication<HystrixClientStarter>(*args)
}

application.yml配置

server:
  port: 6602

spring:
  application:
    name: hystrix-client

再写一个简单的Controller来试一下效果。

@RestController
class DemoController {

    @RequestMapping("hello")
    @HystrixCommand(fallbackMethod = "fallback")
    fun hello(@RequestParam("name") name: String): String {
        throw Exception("test exception")               // throw test exception here
        return "hello $name."
    }


    fun fallback(name: String): String {
        return "fallback function: hello $name."
    }
}

@HystrixCommand 注解来为一个方法增加熔断的能力。只需要定义一个和目标方法(上述例子为hello())结构一致的方法,在注解中传入即可。
为了测试,目标方法中故意抛了一个异常来模拟微服务异常。
访问 http://localhost:6602/hello?name=czb1n 会显示:

fallback function: hello czb1n.

HystrixDashboard

Hystrix还提供了一个数据指标面板工具,HystrixDashboard。不过这个工具没有在Hystrix包里,需要另外导入。

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

启动类中要增加 @EnableHystrixDashboard 注解来启动面板。
面板中的指标数据来自于SpringBoot的actuator
所以要加入actuator的依赖的同时,还要修改application.yml来暴露Hystrix相关的节点指标。

management:
  endpoints:
    web:
      exposure:
        include: hystrix.stream

启动访问http://localhost:6602/actuator/hystrix.stream 就可以看到指标数据。
访问 http://localhost:6602/hystrix 就能打开HystrixDashboard的界面。输入上述的stream就能监控对应的指标。

image

其他

图片均来自SpringCloudNetflix官方文档

示例代码地址: https://github.com/czb1n/learn-spring-cloud-with-kotlin

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值