两者都能实现降级,但fallbackFactory能得到服务降级的原因。
FeignAPI和Fallback代码如下:
@FeignClient(name = "shared-geoip", fallback = GeoIPRemote.HystrixFallback.class)
public interface GeoIPRemote {
@RequestMapping(method = RequestMethod.GET, value = "/geo/get_ip_info")
ResponseMessage getIpInfo(@RequestParam("host") String host);
@Component
class HystrixFallback implements GeoIPRemote {
@Override
public ResponseMessage getIpInfo(String ip) {
return ResponseMessage.buildFail(ResponseCode.SERVICE_BUSY, "IP分析服务");
}
}
}
当服务降级的时候,fallback中只能打印此次调用失败的log,而无法打印详细的异常信息,这明显不符合我们的要求。
@FeignClient(name = "shared-geoip", fallbackFactory = GeoIPRemote.HystrixFallbackFactory.class)
public interface GeoIPRemote {
@RequestMapping(method = RequestMethod.GET, value = "/geo/get_ip_info")
ResponseMessage getIpInfo(@RequestParam("host") String host);
@Component
class HystrixFallbackFactory implements FallbackFactory {
@Override
public GeoIPRemote create(Throwable throwable) {
//此处可以得知异常原因,比如远程服务掉线,服务异常等原因
LogUtils.error(throwable, "errorMsg:{}", throwable.getMessage());
return host -> ResponseMessage.buildFail(ResponseCode.SERVICE_BUSY, "IP分析服务");
}
}
}
2021-06-10 11:14:22.832 [INFO BEGIN] [PollingServerListUpdater-0]:com.netflix.config.ChainedDynamicProperty - [checkAndFlip:115] Flipping property: shared-geoip.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647 [INFO END]
2021-06-10 11:14:22.832.912 [ERROR BEGIN] [hystrix-shared-geoip-1]:c.t.t.p.r.h.HystrixFallbackFactory - [create:26] Connection refused: connect executing POST http://shared-geoip/geo/get_ip_info [ERROR END]
2020-10-30 15:14:22.912 [ERROR BEGIN] [hystrix-shared-geoip-1-1]:c.t.t.p.r.h.FallbackFactory- [GeoIPRemote :60] errorMsg:Connection refused [ERROR END]
当服务降级的时候,fallbackFactory中既打印此次调用失败的log,也可以打印详细的异常信息,符合要求。
重点关注hystrix的隔离策略有两种:threadpool和semaphore
对比如下:
应用提供外网访问,对于高并发下、机器性能比较好的情况下推荐使用threadpool隔离方式。
详细配置如下,调用方微服务和网关服务可根据实际情况进行适当修改。
feign:
hystrix:
enabled: true #开启降级
ribbon:
#Ribbon允许最大连接数,即所有后端微服务实例请求并发数之和的最大值。
MaxTotalConnections: 500
#单个后端微服务实例能接收的最大请求并发数
MaxConnectionsPerHost: 500
#建议设置超时时间,以免因为等待时间过长造成请求处理失败(一)
#Http请求中的socketTimeout
ReadTimeout: 5000
#Http请求中的connectTimeout
ConnectTimeout: 10000
hystrix:
threadpool:
default:
coreSize: 20 #核心线程数量
maximumSize: 100 #最大线程数量
allowMaximumSizeToDivergeFromCoreSize: true
command:
default:
fallback:
isolation:
thread:
timeoutInMilliseconds: 10000 #命令执行超时时间
execution:
isolation:
thread:
timeoutInMilliseconds: 10000 #请求的超时
timeout:
enabled: true #断路器超时设置
circuitBreaker:
requestVolumeThreshold: 1000 #设置熔断器失败的个数
配置解释链接:https://blog.csdn.net/harris135/article/details/77879148?utm_source=debugrun&utm_medium=distribute.pc_relevant.none-task-blog-title-3&spm=1001.2101.3001.4242