本文提到的類(lèi)均是hadoop框架中的冕屯。
官方文檔提到:
ToolRunner can be used to run classes implementing Tool interface
ToolRunder 是用來(lái)運(yùn)行實(shí)現(xiàn)了Tool
接口的類(lèi),那么實(shí)現(xiàn)了Tool接口的類(lèi)能做到什么送爸?
Tool 接口繼承了Configurable
接口,換言之火诸,實(shí)現(xiàn)Tool必須實(shí)現(xiàn)三個(gè)接口:
public class AnalysisTool implements Tool {
@Override
public int run(String[] args) throws Exception {
return 0;
}
@Override
public void setConf(Configuration conf) {
}
@Override
public Configuration getConf() {
return null;
}
}
代碼中该窗,run
方法 表示給定參數(shù)并執(zhí)行對(duì)應(yīng)的MR應(yīng)用。后兩個(gè)方法當(dāng)然就是設(shè)定和獲取配置參數(shù)(不設(shè)置也會(huì)新建)拌消。所以不難想象挑豌,一個(gè)MR應(yīng)用應(yīng)該是由Tool加載配置文件并最終執(zhí)行的。所以官方文檔提到:
Tool, is the standard for any Map-Reduce tool/application. The tool/application should delegate the handling of standard command-line options to ToolRunner.run(Tool, String[]) and only handle its custom arguments.
即墩崩,Tool規(guī)范了MR應(yīng)用氓英。后邊一句話又提到MR應(yīng)用將標(biāo)準(zhǔn)命令行參數(shù)的處理交由ToolRunner.run(Tool, String[])
來(lái)處理。這里是指鹦筹,運(yùn)行MR程序和配置文件都應(yīng)該由ToolRunner來(lái)執(zhí)行铝阐。即,ToolRunnder是運(yùn)行MR程序(Tool封裝的)的官方標(biāo)準(zhǔn)铐拐。
簡(jiǎn)單總結(jié)一下:一個(gè)MR應(yīng)用應(yīng)由ToolRunner的調(diào)用Tool實(shí)現(xiàn)類(lèi)完成徘键,期間需要加載配置文件。
可能有人會(huì)問(wèn)遍蟋?這樣和直接使用main方法執(zhí)行有什么區(qū)別吹害?
實(shí)際上ToolRunner執(zhí)行的應(yīng)用可以接受hadoop標(biāo)準(zhǔn)命令行參數(shù)
比如 hadoop MyHadoopApp -D mapred.reduce.tasks=3
,這樣顯然就會(huì)更靈活/標(biāo)準(zhǔn)虚青。而非標(biāo)準(zhǔn)的參數(shù)它呀,比如輸入輸出路徑,會(huì)傳入到run方法的args中挟憔,以供開(kāi)發(fā)者自己使用钟些。
最終,如果你不用標(biāo)準(zhǔn)命令行參數(shù)的配置绊谭≌校可能看起來(lái)似乎兩種方式?jīng)]什么區(qū)別。但那并是說(shuō)ToolRunner沒(méi)有優(yōu)點(diǎn)达传。
擴(kuò)展
以下是ToolRunner方法的部分源碼實(shí)現(xiàn)篙耗,可以看出:
會(huì)自動(dòng)新建配置對(duì)象
會(huì)將傳入的參數(shù)整合在一起(符合標(biāo)準(zhǔn)的)
將剩余的參數(shù)(輸入輸出路徑等)作為run方法的參數(shù)傳給實(shí)現(xiàn)類(lèi)
if(conf == null) {
conf = new Configuration();
}
GenericOptionsParser parser = new GenericOptionsParser(conf, args);
//set the configuration back, so that Tool can configure itself
tool.setConf(conf);
//get the args w/o generic hadoop args
String[] toolArgs = parser.getRemainingArgs();
return tool.run(toolArgs);