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);
}
}