Hystrix
熔斷器
使用到的依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.0.0.RC1</version>
</dependency>
主啓動類添加註解
@EnableHystrix
現在只是啓動了 Hystrix ,真正使用
方法級別的註解,@HystrixCommand註解,指明熔斷處理類 fallbackMethod 參數要一致:
@GetMapping("/find/{id}")
// 一旦調用服務方法失敗並拋出錯誤信息後,會自動調用 @HystrixCommand 標註的 fallbackMethod 指定的方法
@HystrixCommand(fallbackMethod = "processHystrix_Get")
public Dept get(@PathVariable("id") Long id) {
Dept dept = deptService.findById(id);
if (null == dept) {
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");
}
Feign 中集成了 Hystrix 可以使用類級別的熔斷處理,Feign 中集成了 Hystrix 指定服務降級的 key 是 fallbackFactory
@FeignClient(value = "MICROSERVICECLOUD", fallbackFactory = DeptClientServiceFallback.class)
public interface DeptClientService {
@PostMapping("/dept/add")
public boolean add(@RequestBody Dept dept) ;
@GetMapping("/dept/find/{id}")
public Dept get(@PathVariable("id") Long id) ;
@GetMapping("/dept/list")
public List<Dept> list() ;
}
熔斷類,實現_FallbackFactory_接口
@Component
public class DeptClientServiceFallback implements FallbackFactory<DeptClientService> {
@Override
public DeptClientService create(Throwable throwable) {
return new DeptClientService() {
@Override
public boolean add(Dept dept) {
return false;
}
@Override
public Dept get(Long id) {
return new Dept().setDeptno(id).
setDname("該ID: " + id + " 沒有對應的信息, FallbackFactory<DeptClientService>").
setDb_source("no this database in MySQL");
}
@Override
public List<Dept> list() {
return null;
}
};
}
}
服務監控 HystrixDashboard
添加的依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-hystrix-dashboard</artifactId>
</dependency>
主啓動類的註解
@EnableHystrixDashboard
被監控的類需要添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置很簡單,只要是使用了 Hystrix 的都可以被監控,主要是查看監控信息
注意點:
1. Finchley.RC1 版本的 Spring Cloud 的訪問路徑類似:http://localhost:8001/actuator/hystrix.stream
需要在端口和 hystrix.stream 中間添加 actuator
2. springcloud 的Finchley.RC1 版本中監默認是關閉的,需要在配置中打開
#暴露全部的監控信息
management:
endpoints:
web:
exposure:
include: "*"
3. 在 spring cloud Finchley.RC1 版本中使用 Hystrix ,需要添加 @EnableHystrix
4.解決無法引如 hystrixdashboard 的問題
先加入如下依賴:
<dependency>
<groupId>com.netflix.hystrix</groupId>
<artifactId>hystrix-javanica</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-hystrix-dashboard</artifactId>
</dependency>
上面兩個依賴配合才引入了dashboard,完成後可以刪除上面的改爲下面的依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>