ums_hystrix增加hystrix服务降级(openfeign)

介绍

在 ums 增加 hystrix ,当 getNotice() 无响应 时,会自动调用 fallback() 方法,给客户端返回响应

openfeign 已经集成 hystrix,可以在 @FeignClient 注解指定 服务降级的 备选方法

注意: 主启动类不需要加 @EnableHystrix 注解

创建类 并实现 NoticeClient 接口

当触发服务降级时,会调用该类 对应 的方法

  1. @Component
  2. public class NoticeClientImpl implements NoticeClient {
  3. @Override
  4. public CommonResult<Notice> getNoticeById(String id) {
  5. return new CommonResult<>(100,"getNoticeById:服务繁忙,请您稍后再试!");
  6. }
  7. @Override
  8. public CommonResult sendNotice(Notice notice) {
  9. return new CommonResult<>(101,"sendNotice:服务繁忙,请您稍后再试!");
  10. }
  11. }

修改 NoticeClient 接口

openfeign 是通过该接口调用 服务提供者 的,通过 @FeignClient 注解指定 服务降级时,调用 fallback 方法

增加下面注解

  1. @Component

修改 @FeignClient 注解

修改如下:

  1. @FeignClient(value="NOTICE-SERVICE",fallback = NoticeClientImpl.class)

解释: openfeign 通过该接口调用 服务提供者,假设 调用 getNoticeById() 超时后,触发降级,会调用 NoticeClientImpl 类的 getNoticeById() 方法

缺点

此配置方法无法获得 异常信息,如果想获取 异常信息,需要使用 @FeignClient 注解的 fallbackFactory 属性

参见:https://blog.csdn.net/qq_38149225/article/details/109454418

修改 application.yml

开启hystrix

  1. feign:
  2. hystrix:
  3. enabled: true # 必须为true,hystrix 才生效

指定超时时间(全局配置)

  1. hystrix:
  2. command:
  3. default:
  4. execution:
  5. isolation:
  6. thread:
  7. timeoutInMilliseconds: 500

指定超时时间(针对服务提供者配置)

  1. hystrix:
  2. command:
  3. 服务提供者id:
  4. execution:
  5. isolation:
  6. thread:
  7. timeoutInMilliseconds: 500

服务提供者id,eureka server中微服务的名字,如下图:

测试超时

启动服务

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

访问结果如下:

  1. {
  2. "code": 100,
  3. "msg": "getNoticeById:服务繁忙,请您稍后再试!"
  4. }

原文出处:http://malaoshi.top/show_1IX1Qmft76FY.html