ums_hystrix增加hystrix服务降级(全局配置)

解决思路

  1. 超时不等待。服务提供者 超时、无响应、崩溃,服务调用者 不能一直等待

  2. 报错不抛错。当 接口报错时,不向前端抛出错误

修改pom.xml

增加下面依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

修改 application.yml

开启 hystrix:

feign:
  hystrix:
    enabled: true

修改主启动类

增加下面注解:

@EnableHystrix

完整代码

如下

@SpringBootApplication
@EnableFeignClients
@EnableHystrix
public class UmsHystrixMain {
    public static void main(String[] args) {
        SpringApplication.run(UmsHystrixMain.class,args);
    }
}

修改 FollowController类

当 接口 响应超时、报错,就会触发 服务降级,调用 备选方法(fallback)

增加 fallback() 方法

服务降级时,执行该方法

public JsonResult fallback(){
    return new JsonResult(100,"hystrix降级(全局)!");
}

注意:

  1. fallback方法 返回值 必须与 熔断方法 相同(如果有泛型,泛型也要相同)
  2. fallback方法 参数列表 必须与 熔断方法 相同
  3. 尽量把熔断添加再最外层的方法中

在类上增加注解

@DefaultProperties(defaultFallback = "fallback")

解释: 服务降级时,调用 当前类的 fallback() 方法

给接口增加注解

由于 getNotice() 接口 需要调用 服务提供者 的接口,所以 getNotice() 接口 需要服务降级,防止因为 服务提供者 的接口慢而拖死

增加下面注解:

@HystrixCommand(commandProperties = {
        @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "1500")})

解释: 超过1500毫秒无响应时,那么就 调用 @DefaultProperties 注解指定的 fallback() 方法

测试超时

启动服务

访问 http://localhost:8081/getNotice/195c6547e5044c759dc39caf317998c5

getNotice 接口需要调用 notice 工程的 getNoticeById 接口,而 getNoticeById 接口休眠 3 秒中,也就是说 getNotice 接口也需要等待 3 秒,带 通过 @HystrixCommand 注解的配置,当超过 1.5秒 没有响应时,就会调用 fallback() 方法

访问结果如下:

{
    "code": 100,
    "msg": "hystrix降级(全局)!"
}

测试报错

修改 getNotice() 方法

修改 getNotice() 方法,在首行增加下面代码:

int i=1/0;

完整代码如下:

@HystrixCommand(commandProperties = {
        @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "1500")})
@GetMapping(value="/getNotice/{id}")
public JsonResult getNotice(@PathVariable("id") String id){
    int i=1/0;
    logger.info("id="+id);
    return noticeClient.getNoticeById(id);
}

访问测试

访问 http://localhost:8081/getNotice/195c6547e5044c759dc39caf317998c5

在控制台中没有打印异常信息,访问结果如下:

{
    "code": 100,
    "msg": "hystrix降级(全局)!"
}

全局配置的缺点

  1. 全局配置,当超时、报错后,都执行 同一个 备选方法。但有时,需要执行其他的 备选方法,需要单独配置

  2. 备选方法 无法获得 原方法的参数。如果需要获得 原方法的参数,需要单独配置