SpringCloud系列九:Hystrix-服务熔断

 服务熔断:熔断机制是应对雪崩效应的一种微服务链路保护机制。当扇出链路的某个微服务不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回"错误"的响应信息。当检测到该节点微服务调用响应正常后恢复调用链路。在SpringCloud框架里熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,当失败的调用到一定阈值,缺省是5秒内20次调用失败就会启动熔断机制。熔断机制的注解是@HystrixCommand。
1、参考部门提供者工程microservicecloud-provider-dept-8001新建microservicecloud-provider-dept-hystrix工程
2、引入依赖

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

3、修改类DeptController

@RestController
public class DeptController {

    @Autowired
    private DeptService service = null;

    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
    //一旦调用服务方法失败并抛出了错误信息后,会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
    @HystrixCommand(fallbackMethod = "processHystrix")
    public Dept get(@PathVariable("id") Long id) {
        Dept dept = this.service.get(id);
        if (null == dept) {
            throw new RuntimeException("该ID:" + id + "没有对应的信息");
        }
        return dept;
    }

    public Dept processHystrix(@PathVariable("id") Long id) {
        return new Dept().setDeptno(id).setDname("该ID:" + id + "没有对应的信息,null--@HystrixCommand")
                .setDb_source("no this database in MySQL");
    }
}

4、在主启动类添加@EnableCircuitBreaker注解

@SpringBootApplication
@EnableEurekaClient    //开启服务注册
@EnableDiscoveryClient    //开启服务发现
@EnableHystrix    //开启Hystrix熔断机制
public class DeptProviderHystrix_App {
    public static void main(String[] args) {
        SpringApplication.run(DeptProviderHystrix_App.class, args);
    }
}

5、先启动3个eureka集群后,启动hystrix工程,再启动部门消费者。
http://localhost:9001/consumer/dept/get/1
在这里插入图片描述
http://localhost:9001/consumer/dept/get/235
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/lizhiqiang1217/article/details/89813400