一、引入Hystrix相关的jar
<!-- hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
二、主启动类开启服务熔断(服务生产者开启即可) @EnableCircuitBreaker
@SpringBootApplication
@EnableEurekaClient//本服务启动后会自动注册进Eureka服务中
@EnableCircuitBreaker//对hystrixR熔断机制的支持
public class DeptProvider8001_Hystrix_App {
public static void main(String[] args) {
SpringApplication.run(DeptProvider8001_Hystrix_App.class, args);
}
}
三、编写服务熔断案例(服务生产者)
服务熔断一般是指软件系统中,由于某些原因使得服务出现了过载现象,为防止造成整个系统故障,从而采用的一种保护措施,所以很多地方把熔断亦称为过载保护。
@RestController
public class DeptController {
@Autowired
private DeptService service = null;
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
@HystrixCommand(fallbackMethod = "processHystrix_Get")
public Dept get(@PathVariable("id") Long id) {
Dept dept = this.service.get(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");
}
}
测试:
四、编写服务降级案例(服务消费者)
服务降级一般是指整体资源快不够了,忍痛将某些服务先关掉,待渡过难关,再开启回来。
1)、全局配置添加,开启服务降级
feign:
hystrix:
enabled: true
2)、编写降级后的业务提示
@Component
public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService>{
@Override
public DeptClientService create(Throwable cause) {
// TODO Auto-generated method stub
return new DeptClientService() {
@Override
public Dept get(long id) {
return new Dept().setDeptno(id).setDname("该ID:" + id + "没有没有对应的信息,null--@HystrixCommand")
.setDb_source("no this database in MySQL");
}
@Override
public List<Dept> list() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean add(Dept dept) {
// TODO Auto-generated method stub
return false;
}
};
}
}
3)、服务消费者调用业务逻辑,当生产者服务关闭以后会走2)定义的方法
@RestController
public class DeptController_Consumer {
@Autowired
private DeptClientService service = null;
@RequestMapping(value = "/consumer/dept/get/{id}")
public Dept get(@PathVariable("id") Long id) {
return this.service.get(id);
}
@RequestMapping(value = "/consumer/dept/list")
public List<Dept> list() {
return this.service.list();
}
@RequestMapping(value = "/consumer/dept/add")
public Object add(Dept dept) {
return this.service.add(dept);
}
}