本文主要總結Elasticsearch 自定義 REST 接口的插件開發流程。
1. 插件介紹
本插件邏輯比較簡單,主要用來返回包含指定前綴的節點列表。
2. 代碼說明
插件主要包括兩部分的內容,一部分用來對插件的註冊,另一部分負責對業務邏輯的處理
插件註冊部分:
public class CustomerRestActionPlugin extends Plugin implements ActionPlugin {
public CustomerRestActionPlugin(){
super();
System.out.println("Plugin for node name search");
}
@Override
public List<Class<? extends RestHandler>> getRestHandlers() {
return Collections.singletonList(CustomerRestAction.class);
}
}
業務邏輯處理部分:
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient nodeClient) throws IOException {
final String nodePrefix = restRequest.param("prefix", "");
return (channel) -> {
nodeClient.admin().cluster().prepareNodesInfo().all().execute(new RestBuilderListener<NodesInfoResponse>(channel) {
@Override
public RestResponse buildResponse(NodesInfoResponse nodesInfoResponse, XContentBuilder xContentBuilder) throws Exception {
List<String> nodes = new ArrayList<String>();
for (NodeInfo nodeInfo : nodesInfoResponse.getNodes()) {
if (nodePrefix.isEmpty()) {
nodes.add(nodeInfo.getNode().getName());
} else if (nodeInfo.getNode().getName().startsWith(nodePrefix)) {
nodes.add(nodeInfo.getNode().getName());
}
}
xContentBuilder.startObject().field("nodes", nodes).endObject();
return new BytesRestResponse(RestStatus.OK, xContentBuilder);
}
});
};
}
3. 打包部署
3.1 打包與部署
通過以下命令生成壓縮包,壓縮包中主要包括jar文件,配置文件等。
mvn clean package
通過執行該命令,在target/release目錄下會生成名稱爲elasticsearch-esext-5.1.1.zip的壓縮包
3.2 部署
- 在elasticsearch/plugins目錄下,創建CustomerRestActionPlugin子目錄
- 將該壓縮包解壓縮到CustomerRestActionPlugin目錄下
- 重啓ES
3.3 驗證
執行已下命令,查看返回結果
curl -XGET 'localhost:9200/_masting/nodes?prefix=test'
4. Git代碼
完整代碼,可從 https://github.com/Eric-aihua/esext.git 獲取