【SrpingCloud】三、Hystrix 熔断机制的实现
一、添加Hystrix依赖
<!-- Hystrix-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
二、没有熔断机制时,只会返回错误页面
@GetMapping("/dept/get/{id}")
public Dept get(@PathVariable("id") Integer id){
Dept dept = deptService.queryId(id);
if (dept == null){
throw new RuntimeException("id=>" + id + "is not presence");
}
return dept;
}
- 上述代码实现了一个基本的查询,当输入 :http://localhost:8002/dept/get/1 时,会出现
- 查询成功
- 当输入 : http://localhost:8002/dept/get/10000 时,数据库中没有这样的数据,会出现
- 错误页面
三、添加熔断机制,隐藏错误页面,返回自定义内容
- @ HystrixCommand(fallbackMethod = “HystrixGet”) :发生熔断时:触发 HystrixGet 方法
- HystrixGet 方法是自定义方法,详细看下面代码
@GetMapping("/dept/get/{id}")
@HystrixCommand(fallbackMethod = "HystrixGet")
public Dept get(@PathVariable("id") Integer id){
Dept dept = deptService.queryId(id);
if (dept == null){
throw new RuntimeException("id=>" + id + "is not presence");
}
return dept;
}
public Dept HystrixGet(@PathVariable("id") Integer id){
Dept a = new Dept();
a.setDeptno(id);
a.setDname("id=>" + id + "不存在该用户,null--@hystrix");
a.setDb_source("no this databases in MySql");
return a;
}
- 效果如下: