前面的幾節(jié)我們重點(diǎn)分析了Hystrix的整個(gè)流程以及工作原理汇在,以及基于@HystrixCommand注解使用方式之后的流程分析,這一節(jié)我們主要結(jié)合實(shí)際應(yīng)用Zuul網(wǎng)關(guān)層來進(jìn)一步分析Zuul網(wǎng)關(guān)里面是如何應(yīng)用Hystrix熔斷的脏答!
這里我們引用Zuul官方的一張過濾器周期圖糕殉,Zuul的核心功能就是filter,這里我們也能直觀的看出殖告,請求下游服務(wù)(Origin Server)是在routing filters這類路由過濾器進(jìn)行阿蝶,而Zuul的Filters過濾器核心執(zhí)行邏輯在ZuulServlet,ZuulServlet繼承HttpServlet作為總的執(zhí)行入口黄绩,內(nèi)部就會(huì)執(zhí)行上述的ZuulFilter過濾器生命周期赡磅,那么下面我們就直接進(jìn)入重點(diǎn),看看我們的Hystrix是怎么被利用起來的宝与!
EnableZuulProxy入口配置
@EnableCircuitBreaker
@EnableDiscoveryClient
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(ZuulProxyConfiguration.class)
public @interface EnableZuulProxy {
}
當(dāng)我們使用某一個(gè)框架的時(shí)候焚廊,我們關(guān)心最多的一個(gè)問題莫過于它的入口在哪里?從入口進(jìn)行分析無疑會(huì)減少很多工作量习劫,@EnableZuulProxy直接作用在應(yīng)用入口類咆瘟,然后我們看看引入了ZuulProxyConfiguration這個(gè)配置類,那我們接著看看ZuulProxyConfiguration配置
ZuulProxyConfiguration
@Configuration
@Import({ RibbonCommandFactoryConfiguration.RestClientRibbonConfiguration.class,
RibbonCommandFactoryConfiguration.OkHttpRibbonConfiguration.class,
RibbonCommandFactoryConfiguration.HttpClientRibbonConfiguration.class })
public class ZuulProxyConfiguration extends ZuulConfiguration {
......
// route filters
@Bean
public RibbonRoutingFilter ribbonRoutingFilter(ProxyRequestHelper helper,
RibbonCommandFactory<?> ribbonCommandFactory) {
RibbonRoutingFilter filter = new RibbonRoutingFilter(helper, ribbonCommandFactory, this.requestCustomizers);
return filter;
}
......
}
因?yàn)檫@一節(jié)我們是分析Hystrix如何被使用起來的诽里,所以我們只需要關(guān)心RibbonRoutingFilter這個(gè)route類型的filters袒餐,因?yàn)檫@種filter才會(huì)請求下游服務(wù)
RibbonRoutingFilter
public class RibbonRoutingFilter extends ZuulFilter {
......
//當(dāng)前過濾器是否生效
@Override
public boolean shouldFilter() {
RequestContext ctx = RequestContext.getCurrentContext();
//配置的routes路由為使用serviceId方式,不是直連的url配置方式
return (ctx.getRouteHost() == null && ctx.get(SERVICE_ID_KEY) != null
&& ctx.sendZuulResponse());
}
//過濾器執(zhí)行方法
@Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
//添加忽略的頭信息,zuul的ignored-headers配置,會(huì)過濾這些頭信息參數(shù)
this.helper.addIgnoredHeaders();
try {
//構(gòu)建Ribbon命令執(zhí)行的上下文,保存相關(guān)參數(shù)的對象
RibbonCommandContext commandContext = buildCommandContext(context);
//轉(zhuǎn)發(fā)請求灸眼,調(diào)用下游服務(wù)
ClientHttpResponse response = forward(commandContext);
setResponse(response);
return response;
}
catch (ZuulException ex) {
throw new ZuulRuntimeException(ex);
}
catch (Exception ex) {
throw new ZuulRuntimeException(ex);
}
}
//主要就是封裝參數(shù)卧檐,封裝頭信息、請求參數(shù)信息...
protected RibbonCommandContext buildCommandContext(RequestContext context) {
HttpServletRequest request = context.getRequest();
MultiValueMap<String, String> headers = this.helper
.buildZuulRequestHeaders(request);
MultiValueMap<String, String> params = this.helper
.buildZuulRequestQueryParams(request);
String verb = getVerb(request);
InputStream requestEntity = getRequestBody(request);
if (request.getContentLength() < 0) {
context.setChunkedRequestBody();
}
String serviceId = (String) context.get(SERVICE_ID_KEY);
Boolean retryable = (Boolean) context.get(RETRYABLE_KEY);
String uri = this.helper.buildZuulRequestURI(request);
uri = uri.replace("http://", "/");
long contentLength = useServlet31 ? request.getContentLengthLong(): request.getContentLength();
return new RibbonCommandContext(serviceId, verb, uri, retryable, headers, params,
requestEntity, this.requestCustomizers, contentLength);
}
//轉(zhuǎn)發(fā)請求/調(diào)用下游服務(wù)
protected ClientHttpResponse forward(RibbonCommandContext context) throws Exception {
Map<String, Object> info = this.helper.debug(context.getMethod(),
context.getUri(), context.getHeaders(), context.getParams(),
context.getRequestEntity());
//封裝RibbonCommand對象焰宣,內(nèi)部繼承HystrixExecutable霉囚,這樣就可以使用Hystrix的功能
RibbonCommand command = this.ribbonCommandFactory.create(context);
try {
//執(zhí)行命令,調(diào)用下游服務(wù)匕积,最終調(diào)用到HystrixCommand#execute()盈罐,
//這樣實(shí)現(xiàn)類通過實(shí)現(xiàn)Hystrix的run()、getFallback()方法就可以使用Hystrix的熔斷功能了
ClientHttpResponse response = command.execute();
this.helper.appendDebug(info, response.getStatusCode().value(),
response.getHeaders());
return response;
}
catch (HystrixRuntimeException ex) {
return handleException(info, ex);
}
}
......
}
在RibbonRoutingFilter這個(gè)過濾器通過片段中的代碼注釋信息闪唆,我們得知其實(shí)這個(gè)過濾器就做了一件事盅粪,那就是使用Hystrix的功能,把Hystrix引入進(jìn)來悄蕾,這樣就把調(diào)用下游服務(wù)的任務(wù)交給了Hystrix票顾,通過Hystrix來判斷下游是否需要熔斷等情況!
HttpClientRibbonCommandFactory
我們回過頭繼續(xù)看下ZuulProxyConfiguration配置類中通過@Import方式引入了RestClientRibbonConfiguration帆调、OkHttpRibbonConfiguration奠骄、HttpClientRibbonConfiguration,此處我們的應(yīng)用基于httpclient方式贷帮,那我們就只分析下HttpClientRibbonConfiguration的配置戚揭,其他方式大致都是一樣的邏輯
public class HttpClientRibbonCommandFactory extends AbstractRibbonCommandFactory {
......
//創(chuàng)建RibbonCommand
@Override
public HttpClientRibbonCommand create(final RibbonCommandContext context) {
//降級實(shí)現(xiàn)類诱告,默認(rèn)null
ZuulFallbackProvider zuulFallbackProvider = getFallbackProvider(context.getServiceId());
//獲取serviceId撵枢,如@FeignClient注解中的value字段
final String serviceId = context.getServiceId();
//獲取RibbonLoadBalancingHttpClient客戶端
//默認(rèn)在Ribbon的RibbonClientConfiguration#HttpClientRibbonConfiguration中注冊
final RibbonLoadBalancingHttpClient client = this.clientFactory.getClient(
serviceId, RibbonLoadBalancingHttpClient.class);
//設(shè)置負(fù)載均衡器ILoadBalancer
client.setLoadBalancer(this.clientFactory.getLoadBalancer(serviceId));
//返回封裝了參數(shù)的HttpClientRibbonCommand,內(nèi)部繼承AbstractRibbonCommand
return new HttpClientRibbonCommand(serviceId, client, context, zuulProperties, zuulFallbackProvider,
clientFactory.getClientConfig(serviceId));
}
}
上面HttpClientRibbonCommandFactory中最重要的一件事情精居,獲取Ribbon的RibbonLoadBalancingHttpClient然后設(shè)置負(fù)載均衡器锄禽!最后返回了HttpClientRibbonCommand,其繼承了AbstractRibbonCommand靴姿,內(nèi)部就實(shí)現(xiàn)了Hystrix的run()沃但、getFallback()方法
AbstractRibbonCommand
public abstract class AbstractRibbonCommand<LBC extends AbstractLoadBalancerAwareClient<RQ, RS>, RQ extends ClientRequest, RS extends HttpResponse>
extends HystrixCommand<ClientHttpResponse> implements RibbonCommand {
......
//HystrixCommand的run方法實(shí)現(xiàn)
@Override
protected ClientHttpResponse run() throws Exception {
final RequestContext context = RequestContext.getCurrentContext();
//創(chuàng)建一個(gè)請求,此處對應(yīng)RibbonApacheHttpRequest請求
RQ request = createRequest();
//負(fù)載均衡客戶端執(zhí)行負(fù)載均衡請求
RS response = this.client.executeWithLoadBalancer(request, config);
context.set("ribbonResponse", response);
//Hystrix執(zhí)行命令超時(shí)佛吓,則顯示關(guān)閉Http請求
if (this.isResponseTimedOut()) {
if (response != null) {
response.close();
}
}
return new RibbonHttpResponse(response);
}
//HystrixCommand的getFallback降級方法
@Override
protected ClientHttpResponse getFallback() {
if(zuulFallbackProvider != null) {
return zuulFallbackProvider.fallbackResponse();
}
return super.getFallback();
}
......
}
通過分析我們能得知最終的一個(gè)請求流程為:客戶端發(fā)起請求->HttpServlet-> ZuulServlet->routing filters->Hystrix->Ribbon->返回結(jié)果給客戶端,至此我們分析了Hystrix在實(shí)際應(yīng)用中(Zuul網(wǎng)關(guān))的一個(gè)大致實(shí)現(xiàn)宵晚,當(dāng)然Zuul的功能也遠(yuǎn)非如此,Zuul的功能十分強(qiáng)大,在后續(xù)的總結(jié)里會(huì)單獨(dú)分析Zuul網(wǎng)關(guān)维雇!