06.1 Hystrix服务熔断

熔断机制是应对雪崩效应的一种微服务链路保护机制。

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

1. 创建工程

参考microservicecloud-provider-dept-8001, 新建microservicecloud-provider-dept-hystrix-8001

2. pom.xml文件

与provider-dept-8001相比,pom文件中增加了Hystrix配置

1
2
3
4
5
<!--hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>

3. yml文件

与provider-dept-8001相比,yml中修改了服务注册进入eureka的实例名称

1
instance-id: microservicecloud-dept8001-hystrix

4. 修改DeptController

在精简原来代码的基础上,增加了@HystrixCommand注解,一旦调用服务方法失败并抛出了错误信息后,会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RestController
public class DeptController {
@Autowired
private DeptService service;
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
@HystrixCommand(fallbackMethod = "processHystrix_Get")
public Dept get(@PathVariable("id") Long id) {
Dept dept = service.get(id);
if (dept == null) {
throw new RuntimeException("该ID:" + id + "没有对应的信息");
}
return dept;
}
public Dept processHystrix_Get(@PathVariable("id") Long id) {
return new Dept().setDeptno(id)
.setDname("该ID:" + id + "没有对应的信息,null--@HystrixCommand")
.setDb_source("no this database in MySQL");
}
}

5. 主启动类修改

1
2
3
4
5
6
7
8
9
10
11
12
@SpringBootApplication
// 本服务启动后会自动注册进 eureka 服务中
@EnableEurekaClient
// 服务发现
@EnableDiscoveryClient
// 对hystrix熔断机制的支持
@EnableCircuitBreaker
public class ProviderDeptHystrix8001Application {
public static void main(String[] args) {
SpringApplication.run(ProviderDeptHystrix8001Application.class, args);
}
}

6. 验证

首先启动Eureka集群,然后启动provider-dept-hystrix-8001,等待服务注册

最后启动consumer-dept-8001,并访问验证

1
2
3
4
5
6
7
8
9
10
11
12
curl http://localhost/consumer/dept/get/1
{
"deptno": 1,
"dname": "开发部",
"db_source": "cloudDB01"
}
curl http://localhost/consumer/dept/get/112
{
"deptno": 112,
"dname": "该ID:112没有对应的信息,null--@HystrixCommand",
"db_source": "no this database in MySQL"
}

资源获取

公众号回复 : Hystrix服务熔断 获取本节代码

公众号回复 : SpringCloud思维导图

Tips

欢迎收藏和转发,感谢你的支持!(๑•̀ㅂ•́)و✧

欢迎关注我:后端小哥,专注后端开发,希望和你一起进步!