目標(biāo)
明確Zuul的執(zhí)行流程和重要類的分析
Zuul過濾器的生命周期
源碼分析
zuul怎么攔截我們的請(qǐng)求弃衍?
ZuulServletFilter
- 繼承 Filter | ZuulServlet
- 繼承 HttpServlet
可以通過這兩個(gè)類,讓Zuul接管請(qǐng)求。由于他們的邏輯基本一致慈迈,下面用ZuulServletFilter
來分析
/**
* Zuul核心處理類,攔截請(qǐng)求
**/
public class ZuulServletFilter implements Filter {
private ZuulRunner zuulRunner;
// 省略...
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try {
// 初始化requests和responses到RequestContext中,詳見ZuulRunner#init
init((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse);
try {
// 執(zhí)行 filterType=pre 的過濾器
preRouting();
} catch (ZuulException e) {
// 執(zhí)行 filterType=error 的過濾器
error(e);
postRouting();
return;
}
// Only forward onto to the chain if a zuul response is not being sent
if (!RequestContext.getCurrentContext().sendZuulResponse()) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
try {
// 執(zhí)行 filterType=route 的過濾器
routing();
} catch (ZuulException e) {
error(e);
postRouting();
return;
}
try {
// 執(zhí)行 filterType=post 的過濾器
postRouting();
} catch (ZuulException e) {
error(e);
return;
}
} catch (Throwable e) {
error(new ZuulException(e, 500, "UNCAUGHT_EXCEPTION_FROM_FILTER_" + e.getClass().getName()));
} finally {
// 清空線程變量
RequestContext.getCurrentContext().unset();
}
}
}
以上方法核心步驟:
初始化請(qǐng)求上下文
RequestContext
執(zhí)行 pre宽气、route肠缨、post過濾器逆趋,如果有錯(cuò),執(zhí)行error過濾器
ZuulRunner
- 初始化RequestContext
中的requests和responses并轉(zhuǎn)發(fā)Filter相關(guān)方法到FilterProcessor
public class ZuulRunner {
private boolean bufferRequests;
// 省略...
/**
* 初始化RequestContext:生成請(qǐng)求和響應(yīng)wapper保存
* RequestContext:繼承了ConcurrentHashMap晒奕,是一個(gè)Map容器闻书,主要存放請(qǐng)求、響應(yīng)供ZuulFilters使用脑慧。
*/
public void init(HttpServletRequest servletRequest, HttpServletResponse servletResponse) {
RequestContext ctx = RequestContext.getCurrentContext();
if (bufferRequests) {
ctx.setRequest(new HttpServletRequestWrapper(servletRequest));
} else {
ctx.setRequest(servletRequest);
}
ctx.setResponse(new HttpServletResponseWrapper(servletResponse));
}
/**
* executes "post" filterType ZuulFilters
*
* @throws ZuulException
*/
public void postRoute() throws ZuulException {
FilterProcessor.getInstance().postRoute();
}
// 省略route() preRoute() error() 方法
}
以上看出Zuul是通過ZuulServletFilter
以filter的方式(或者以ZuulServlet
以servlet的方式)攔截或者承接我們的請(qǐng)求魄眉,并在doFilter
方法(service
方法)中處理各種類型的ZuulFilters,并通過ZuulRunner
轉(zhuǎn)發(fā)到FilterProcessor
中找到對(duì)應(yīng)的filter并執(zhí)行相關(guān)邏輯闷袒。整個(gè)大致流程比較簡(jiǎn)單清晰坑律,類似于設(shè)計(jì)模式中的門面模式。
? 其中囊骤,RequestContext
是存在ThreadLocal
當(dāng)中晃择,可以注意到當(dāng)Zuul處理完畢之后,會(huì)清空線程變量RequestContext
,以防止內(nèi)存泄露也物。
FilterProcessor
怎么找到相應(yīng)ZuulFilters并執(zhí)行呢宫屠?
FilterProcessor
- 執(zhí)行filters的核心類
/**
* 執(zhí)行對(duì)應(yīng)階段ZuulFilters
* sType:即為filterType,例如"post"滑蚯、"pre"激况、"route"、"error"
*
*/
public Object runFilters(String sType) throws Throwable {
if (RequestContext.getCurrentContext().debugRouting()) {
Debug.addRoutingDebug("Invoking {" + sType + "} type filters");
}
boolean bResult = false;
// 獲取已經(jīng)注冊(cè)了的ZuulFilters膘魄,根本是從FilterRegistry中獲取乌逐。并且list是已經(jīng)排好序的,
// 根據(jù)給定的filterOrder
List<ZuulFilter> list = FilterLoader.getInstance().getFiltersByType(sType);
if (list != null) {
for (int i = 0; i < list.size(); i++) {
ZuulFilter zuulFilter = list.get(i);
// 執(zhí)行ZuulFilter邏輯并
Object result = processZuulFilter(zuulFilter);
if (result != null && result instanceof Boolean) {
bResult |= ((Boolean) result);
}
}
}
return bResult;
}
/**
* 執(zhí)行ZuulFilter创葡,并把執(zhí)行情況組合成ZuulFilterResult并返回
*/
public Object processZuulFilter(ZuulFilter filter) throws ZuulException {
// 省略部分代碼...
// 具體執(zhí)行在 ZuulFilter#runFilter
ZuulFilterResult result = filter.runFilter();
ExecutionStatus s = result.getStatus();
switch (s) {
case FAILED:
t = result.getException();
ctx.addFilterExecutionSummary(filterName, ExecutionStatus.FAILED.name(), execTime);
break;
case SUCCESS:
o = result.getResult();
ctx.addFilterExecutionSummary(filterName, ExecutionStatus.SUCCESS.name(), execTime);
default:
break;
}
if (t != null) throw t;
// 統(tǒng)計(jì)每個(gè)filter的每次執(zhí)行情況
usageNotifier.notify(filter, s);
return o;
}
以上方法核心步驟:
按序執(zhí)行各階段ZuulFilters
記錄ZuulFilter執(zhí)行結(jié)果
統(tǒng)計(jì)執(zhí)行情況
ZuulFilter
- 最基本的Filter抽象類浙踢,自定義的Filter是繼承此Filter,FilterProcessor
執(zhí)行Filter最終會(huì)轉(zhuǎn)發(fā)到此類的runFilter
方法
public ZuulFilterResult runFilter() {
// 執(zhí)行結(jié)果以及執(zhí)行成功與否情況包裝成ZuulFilterResult返回
ZuulFilterResult zr = new ZuulFilterResult();
// 此filter是已被archaius禁用 「archaius是netflix開源的動(dòng)態(tài)屬性配置框架」
if (!isFilterDisabled()) {
// 執(zhí)行自定filter的shouldFilter方法判斷是否執(zhí)行此filter
if (shouldFilter()) {
Tracer t = TracerFactory.instance().startMicroTracer("ZUUL::" + this.getClass().getSimpleName());
try {
Object res = run();
zr = new ZuulFilterResult(res, ExecutionStatus.SUCCESS);
} catch (Throwable e) {
t.setName("ZUUL::" + this.getClass().getSimpleName() + " failed");
zr = new ZuulFilterResult(ExecutionStatus.FAILED);
zr.setException(e);
} finally {
t.stopAndLog();
}
} else {
zr = new ZuulFilterResult(ExecutionStatus.SKIPPED);
}
}
return zr;
}
Zuul把ZuulFilters存儲(chǔ)在類FilterLoader
屬性名為hashFiltersByType
的ConcurrentHashMap
中灿渴,key為filterType(eg: pre洛波、route、post骚露、error或者自定義)
那么問題來了蹬挤,這些存在于FilterLoader
的ZuulFilter是怎么加載進(jìn)來的呢?
ZuulFIlter的加載
通過層層搜索棘幸,找到類FilterFileManager
焰扳,在此類初始化的時(shí)候,會(huì)到指定路徑下讀取指定文件。同時(shí)在初始時(shí)吨悍,會(huì)創(chuàng)建守護(hù)線程來定時(shí)掃描加載文件扫茅。
public class FilterFileManager {
// 省略代碼...
public static void init(int pollingIntervalSeconds, String... directories) throws Exception, IllegalAccessException, InstantiationException {
if (INSTANCE == null) INSTANCE = new FilterFileManager();
INSTANCE.aDirectories = directories;
// 守護(hù)線程的輪詢間隔時(shí)間
INSTANCE.pollingIntervalSeconds = pollingIntervalSeconds;
// 讀取并處理文件
INSTANCE.manageFiles();
// 開啟文件掃描的守護(hù)線程
INSTANCE.startPoller();
}
void manageFiles() throws Exception, IllegalAccessException, InstantiationException {
// 讀取文件
List<File> aFiles = getFiles();
// 通過FilterLoader來處理文件
processGroovyFiles(aFiles);
}
// 掃描指定目錄下的指定類型文件
List<File> getFiles() {
List<File> list = new ArrayList<File>();
for (String sDirectory : aDirectories) {
if (sDirectory != null) {
File directory = getDirectory(sDirectory);
// Zuul有自帶類`GroovyFileFilter`是掃描 .groovy 文件.
File[] aFiles = directory.listFiles(FILENAME_FILTER);
if (aFiles != null) {
list.addAll(Arrays.asList(aFiles));
}
}
}
return list;
}
// 開啟守護(hù)線程進(jìn)行輪詢
void startPoller() {
poller = new Thread("GroovyFilterFileManagerPoller") {
public void run() {
while (bRunning) {
try {
sleep(pollingIntervalSeconds * 1000);
manageFiles();
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
poller.setDaemon(true);
poller.start();
}
}
public class FilterLoader {
// 處理文件
public boolean putFilter(File file) throws Exception {
String sName = file.getAbsolutePath() + file.getName();
// 判斷如果文件被修改過,則刪除對(duì)應(yīng)已經(jīng)注冊(cè)的filter
if (filterClassLastModified.get(sName) != null && (file.lastModified() != filterClassLastModified.get(sName))) {
LOG.debug("reloading filter " + sName);
filterRegistry.remove(sName);
}
ZuulFilter filter = filterRegistry.get(sName);
if (filter == null) {
// 編譯文件 - zuul自帶GroovyCompiler編譯groovy編寫的文件
Class clazz = COMPILER.compile(file);
// 如果不是抽象類即ZuulFilter育瓜,則進(jìn)行實(shí)例化并放入內(nèi)存
if (!Modifier.isAbstract(clazz.getModifiers())) {
filter = (ZuulFilter) FILTER_FACTORY.newInstance(clazz);
List<ZuulFilter> list = hashFiltersByType.get(filter.filterType());
if (list != null) {
hashFiltersByType.remove(filter.filterType()); //rebuild this list
}
filterRegistry.put(file.getAbsolutePath() + file.getName(), filter);
filterClassLastModified.put(sName, file.lastModified());
return true;
}
}
return false;
}
}
以上兩個(gè)類核心步驟 即為 FilterFileManager
初始化過程
- 掃描指定目錄下的groovy文件葫隙,通過
FilterLoader
編譯文件,并加載ZuulFilter - 開啟守護(hù)進(jìn)程躏仇,輪詢文件恋脚,動(dòng)態(tài)加載ZuulFilter
總結(jié)
- Zuul的源碼執(zhí)行路徑:
ZuulFilter的加載方式:是通過掃描
.groovy
文件來加載,并支持動(dòng)態(tài)加載焰手,具體可以看官方示例zuul-simple-webappZuul的整個(gè)流程慧起,是基于servlet或filter方式在service或doFilter方法中銜接請(qǐng)求,并運(yùn)用類似門面模式編寫
? 至此册倒,Zuulfilter的加載以及各類型Filter的執(zhí)行都在源碼中找到了蚓挤。zuul-core的代碼還是很容易能看懂。下一篇驻子,會(huì)分析SpringCloud怎么整合Zuul灿意。