NodeClient源代碼
client具體綁定者
在NodeClientModule類中說明了Client被綁定到NodeClient:
bind(Client.class).to(NodeClient.class).asEagerSingleton();
注:NodeClient和TransportClient及其它Client的關(guān)系野舶、作用、區(qū)別會(huì)在接下來地源碼中分析
繼承層次信息
如下圖是NodeClient的繼承信息宰衙,
其父類AbstractClient源碼說明通過NodeClient發(fā)出的請(qǐng)求都通過doExecute()地執(zhí)行來實(shí)現(xiàn)平道,其中g(shù)et方法的調(diào)用堆棧為:
Client.get() <- AbstractClient.execute() <- NodeClient.doExecute() <- TransportAction.execute()
關(guān)鍵調(diào)用源碼:
/**
*AbstractClient.class
* This is the single execution point of *all* clients.
* excute()方法作為所有client的入口方法
*/
@Override
public final <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void execute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
headers.applyTo(request);
listener = threadedWrapper.wrap(listener);
doExecute(action, request, listener);
}
...
@Override
public void get(final GetRequest request, final ActionListener<GetResponse> listener) {
execute(GetAction.INSTANCE, request, listener);
}
類NodeClient作為實(shí)際使用的客戶端,承擔(dān)通過GenericAction和TransportAction的映射選擇實(shí)際TransportAction的責(zé)任供炼。
public class NodeClient extends AbstractClient {
private final ImmutableMap<GenericAction, TransportAction> actions;
...
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
TransportAction<Request, Response> transportAction = actions.get(action);
if (transportAction == null) {
throw new IllegalStateException("failed to find action [" + action + "] to execute");
}
transportAction.execute(request, listener);
}
}
doExecute作為實(shí)際動(dòng)作的執(zhí)行者一屋,在這個(gè)方法中,通過actions的映射獲取實(shí)際的TransportAcion執(zhí)行相應(yīng)的動(dòng)作袋哼。而actions被注入的代碼在ActionModule類中:
registerAction(GetAction.INSTANCE, TransportGetAction.class);
我們進(jìn)一步考察GenericAction和TransportAction的繼承層次會(huì)得出下列源代碼的組織結(jié)構(gòu):
映射結(jié)構(gòu)源代碼結(jié)構(gòu)的組織
以GetAction和TransportGetAction映射為例的源代碼組織如下:
此結(jié)構(gòu)說明對(duì)于每個(gè)GenericAction都有一個(gè)對(duì)應(yīng)的TransportAction
GetAction包括action的名字和一個(gè)具體實(shí)例
public static final GetAction INSTANCE = new GetAction();
public static final String NAME = "indices:data/read/get";
TransportGetAction
為了突出重要代碼冀墨,進(jìn)行了一些簡(jiǎn)化,上述代碼主要有兩個(gè)關(guān)注點(diǎn):
- 繼承層次信息
- GenericAction和TansportAction的映射
待續(xù)
要理解這個(gè)調(diào)用堆棧及其行為需要補(bǔ)充三點(diǎn)信息:
- client具體綁定者
- 具體調(diào)用依據(jù)的源碼
- TransportAction的具體綁定者
TransportAction的具體綁定者
TranportAction的具體綁定者從GenericAction和TansportAction的映射來具體說明涛贯。
GenericAction和TansportAction的映射
此處主要說明下面的內(nèi)容
1.映射結(jié)構(gòu)源代碼結(jié)構(gòu)的組織
2.private final ImmutableMap<GenericAction, TransportAction> actions 地注入
3.為什么要構(gòu)建此映射诽嘉,構(gòu)建此映射的好處是?