Hystrix介绍
官网
https://github.com/Netflix/Hystrix
作用
Hystrix能够保证在一个依赖出问题的情况下,不会导致整体服务失败,避免级联故障,以提高分布式系统的弹性。
能干嘛
服务降级 服务熔断 服务限流 接近实时的监控
遇到一个坑!
idea拷贝项目的时候,最好不要在idea中操作,直接去文件夹里边复制src文件夹! 因为在idea中拷贝,它会去修改“<mapper namespace=”!!!甚至连原本的那份都给改了!
服务熔断/断路器
(针对的是服务端的微服务;有些服务超时或出异常了,直接将它熔断掉(相当于捕获这个异常),不要影响其它n个服务的运行)
依赖
<!-- hystrix --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> <version>1.4.7.RELEASE</version> </dependency>
配置不需要修改
开启注解
@SpringBootApplication @EnableEurekaClient//自动注册到eureka中 @EnableDiscoveryClient//服务发现 @EnableCircuitBreaker//添加对熔断的支持 public class DeptProviderHystrix_8001 { public static void main(String[] args) { SpringApplication.run(DeptProviderHystrix_8001.class,args); } }
服务端代码修改
@RestController public class DeptController { @Autowired private DeptService deptService; @GetMapping("/dept/get/{id}") @HystrixCommand(fallbackMethod = "hystrixGet")//此方法失败了就去调用指定的方法,注意注解顺序!! public Dept get(@PathVariable("id") Long id){ Dept dept = deptService.queryById(id); if(null==dept){ throw new RuntimeException("id==>" + id + ",不存在该用户或信息无法找到~"); } return dept; } //备选方案 public Dept hystrixGet(@PathVariable("id") Long id){ return new Dept() .setDeptno(id) .setDname("id==>" + id + ",没有对应的信息,null~@Hystix") .setDb_source("has no this db in mysql"); } }
服务降级
(针对的是客户端的微服务;服务端降级了,即:只开启一些基本生活保障的服务了,对于那些娱乐类服务的请求,要给它一个提示“暂停营业丶”)
依赖Feign
配置
#开启降级feign.hystrix feign: hystrix: enabled: true
使用
@Component @FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT",fallbackFactory = DeptClientServiceFallbackFactory.class) public interface DeptClientService { @GetMapping("/dept/get/{id}") public Dept queryById(@PathVariable("id") Long id); @GetMapping("/dept/list") public List<Dept> queryAll(); @PostMapping("/dept/add") public boolean addDept(Dept dept); }
//降级~ @Component public class DeptClientServiceFallbackFactory implements FallbackFactory { @Override public DeptClientService create(Throwable throwable) { return new DeptClientService() { @Override public Dept queryById(Long id) { return new Dept() .setDeptno(id) .setDname("id==>"+id+",没有对应的信息,客户端提供了降级的信息,这个服务现在已经被关闭") .setDb_source("没有数据~"); } @Override public List<Dept> queryAll() { return null; } @Override public boolean addDept(Dept dept) { return false; } }; } }
关掉服务端,访问娱乐服务,“暂停营业”,生活保障服务出门右拐丶
Dashboard流监控
(战略性放弃,暂时放弃,实在搞不出来,估计和版本有关系,太费时间了,先搁一下,有机会再从其他项目进来补充)
题外话
所有工程包路径要一致丶
测试
http://eureka7001.com:7001/ http://localhost:8001/dept/get/1 http://localhost:8001/actuator/hystrix.stream http://localhost:9001/hystrix
https://github.com/ChenCurry/springcloud.git