Hystrix理解
熔断器本身是一种开关装置,用于在电路上保护线路过载。当线路中有电器发生短路时,熔断器能够及时切断故障电路,防止发生过载、发热甚至起火等严重后果。这种保护机制被借鉴到分布式系统的设计中,形成了类似Hystrix中的熔断器功能。熔断器在分布式系统中的作用主要是快速失败并返回错误,避免因为某个服务的故障导致整个系统的崩溃。
一、服务熔断
解决的问题
解决服务雪崩效应
1、导入hystrix依赖
<!-- 熔断器 hystrix-->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、使用服务熔断机制
在服务提供者基础上添加服务熔断机制,提供者=>这里!!!
3、控制层部分代码
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
@GetMapping("/dept/get/{id}")
// 使用@HystrixCommand注解标记get方法,并指定fallback方法
@HystrixCommand(fallbackMethod = "hystrixGet")
public Dept get(@PathVariable("id") Long id){
Dept dept = deptService.queryById(id);
if( dept == null ){
throw new RuntimeException("id=>"+id+",不存在该用户信息,或信息无法找到");
}
return dept;
}
// 备选方案
public Dept hystrixGet(@PathVariable("id") Long id){
Dept dept = new Dept();
dept.setDeptno(id)
.setDname("id=>"+id+",不存在该用户信息")
.