介绍
在 ums 增加 hystrix ,当 getNotice()
无响应 时,会自动调用 fallback()
方法,给客户端返回响应
openfeign 已经集成 hystrix,可以在 @FeignClient
注解指定 服务降级的 备选方法
注意: 主启动类不需要加 @EnableHystrix
注解
创建类 并实现 NoticeClient 接口
当触发服务降级时,会调用该类 对应 的方法
@Component
public class NoticeClientImpl implements NoticeClient {
@Override
public CommonResult<Notice> getNoticeById(String id) {
return new CommonResult<>(100,"getNoticeById:服务繁忙,请您稍后再试!");
}
@Override
public CommonResult sendNotice(Notice notice) {
return new CommonResult<>(101,"sendNotice:服务繁忙,请您稍后再试!");
}
}
修改 NoticeClient 接口
openfeign 是通过该接口调用 服务提供者 的,通过 @FeignClient
注解指定 服务降级时,调用 fallback 方法
增加下面注解
@Component
修改 @FeignClient 注解
修改如下:
@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
feign:
hystrix:
enabled: true # 必须为true,hystrix 才生效
指定超时时间(全局配置)
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 500
指定超时时间(针对服务提供者配置)
hystrix:
command:
服务提供者id:
execution:
isolation:
thread:
timeoutInMilliseconds: 500
服务提供者id,eureka server中微服务的名字,如下图:
测试超时
启动服务
访问 http://localhost:8081/getNotice/195c6547e5044c759dc39caf317998c5
访问结果如下:
{
"code": 100,
"msg": "getNoticeById:服务繁忙,请您稍后再试!"
}