Hystri的使用
1.熔断:为了防止服务故障,包含子和下游服务
2.降级:抛弃一些非核心的接口和数据
3.熔断和降级互相交集:
相同点:
1)从可用性和可靠性触发,为了防止系统崩溃
2)最终让用户体验到的是某些功能暂时不可用
不同点:
1)服务熔断一般是下游服务故障 引起的,而服务降级一般是从整体系统负荷考虑,由调用方控制
使用:
1.添加依赖
<!--hystrix依赖,主要是用 @HystrixCommand --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency>
2.在启动类添加注解 @EnableCircuitBreaker
3.在方法中使用
@RequestMapping("save") @HystrixCommand(fallbackMethod = "saveOrderFail") public Object save(@RequestParam("user_id")Integer userId, @RequestParam("product_id")Integer pruductId){ Map<String, Object> msg= new HashMap<>(); msg.put("code",0); msg.put("msg",orderService.save(userId,pruductId)); return msg; } //注意:方法名称一定要与api方法一致 private Object saveOrderFail(Integer userId,Integer productId){ Map<String, Object> msg= new HashMap<>(); msg.put("code",-1); msg.put("msg","抢购人数太多,请稍后再试"); return msg; }
另一种方法:(利用实现Feign的同时底层也实现了Hystrix的特性进行服务熔断和降级,从依赖中可以看出包含关系)
1) 查看Feign依赖注解可以看到如下内容:
2)
1.自定义个降级处理类
@Component public class ProductClientFallback implements ProductClient { @Override public String findById(Integer id) { return "Feign 调用product-service findById 异常"; } }
2.在商品服务客户端中定义fallback:
注意:Feign继承Hystrix默认是关闭的,需要在配置文件中开启Hystrix
feign: hystrix: enable: true