Hystrix服务熔断

Hystrix服务熔断

1、是什么

​ 当扇出链路的某个微服务不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。当检测到该节点微服务调用响应正常后恢复调用链路。在SpringCloud框架里熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是5秒内20次调用失败就会启动熔断机制。熔断机制的注解是@HystrixCommand。

2、在提供者模块导入依赖

<!--Hystrix-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>

3、修改application.yml配置

eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/,http://localhost:7003/eureka/
  instance:
    instance-id: springcloud-provider-dept-hystrix-8001    #修改eureka上的默认描述信息
    prefer-ip-address: true

4、在controller创建

@RequestMapping("/dept/get/{id}")
@HystrixCommand(fallbackMethod = "hystrixGet")
public Dept queryById(@PathVariable("id") Long id){
    Dept dept=service.queryById(id);
    if (dept==null){
        throw new RuntimeException("id=>"+id+",不存在该用户,或信息没有找到");
    }
    return dept;
}
//备选方案
public Dept hystrixGet(@PathVariable("id") Long id){
    return new Dept()
            .setDept_no(id)
            .setDept_name("id=>"+id+"没有对应的信息,@hystrix")
            .setDb_source("no this database in mysql");
}

5、开启服务

在启动类上添加注解

@SpringBootApplication
@EnableEurekaClient     //在服务启动后服务自动注册到Eureka
@EnableDiscoveryClient  // 服务发现
@EnableCircuitBreaker   //添加对熔断的支持
public class Dept_8001 {
    public static void main(String[] args) {
        SpringApplication.run(Dept_8001.class,args);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

芝兰生于深谷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值