SpringCloud五大核心组件

为什么要用Hystrix:

​ 在分布式系统里,一个服务依赖于多个服务,可能在某个服务调用失败后(超时/异常)等,如何能够保证在一个服务处问题的情况下,不会导致整体服务失败,这时就可以通过Hystrix去解决。

Hystrix提供了什么?

​ 熔断、隔离、fallback、cache、监控等功能

熔断后怎么处理?

​ 出现错误之后可以fallback 错误的处理信息 或 兜底数据。

API接口编码实战:

熔断-》降级

  1. ​ pom中添加依赖
  <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

2.在启动类上添加注解:**@EnableCircuitBreaker**/或者**@SpringCloudApplication**

3.编写测试类并添加注解 @HystrixCommand(fallbackMethod = "方法名")

#### 编写fallback方法实现,方法签名一定要和api方法签名一致!!!

```java
 @RequestMapping("save")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(@RequestParam("user_id")int userId, @RequestParam("product_id") int productId){
        Map<String,Object> date = new HashMap<>();
        date.put("code", 0);
        date.put("msg", productOrderService.save(userId, productId));
        return date;
    }
//    注意方法签名一定要和api方法一致
    private Object saveOrderFail(int userId,int productId){
        Map<String,Object> msg = new HashMap<>();
        msg.put("code", -1);
        msg.put("msg", "抢购人数过多,请稍后重试");
        return msg;
    }

4.启动相关服务并登录eureka注册中心检查服务是否已启动成功

5.输入访问接口的url验证可行性,关闭提供者再次尝试访问。

更多推荐

SpringCloud五大核心组件之Hystrix