分佈式緩存一個最重要的應用就是在進行join操作的時候,如果一個表很大,另一個表很小很小,我們就可以將這個小表進行廣播處理,即每個計算節點上都存一份,然後進行map端的連接操作,經過我的實驗驗證,這種情況下處理效率大大高於一般的reduce端join,廣播處理就運用到了分佈式緩存的技術。
DistributedCache將拷貝緩存的文件到Slave節點在任何Job在節點上執行之前,文件在每個Job中只會被拷貝一次,緩存的歸檔文件會被在Slave節點中解壓縮。將本地文件複製到HDFS中去,接着J哦不Client會通過addCacheFile() 和addCacheArchive()方法告訴DistributedCache在HDFS中的位置。當文件存放到文地時,JobClient同樣獲得DistributedCache來創建符號鏈接,其形式爲文件的URI加fragment標識。當用戶需要獲得緩存中所有有效文件的列表時,JobConf 的方法 getLocalCacheFiles() 和getLocalArchives()都返回一個指向本地文件路徑對象數組。
下面貼一下我的部分代碼:
在run函數中
DistributedCache.createSymlink(job.getConfiguration());//
try {//#的作用是以後用的時候直接input就可以了
DistributedCache.addCacheFile(new URI(args[1]+"/#input"), job.getConfiguration());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
在map端打開分佈式緩存的文件並讀如Hashtable中
private Hashtable<String, DefinedMyself> word_hash = new Hashtable<String,DefinedMyself>();
public void setup(Context context) throws IOException, InterruptedException{
String[] selected_region = null;
Path p[] = DistributedCache.getLocalCacheFiles(context.getConfiguration());
FileReader reader = new FileReader("input");
BufferedReader br = new BufferedReader(reader);
System.out.println("this is OK");
String s1 = null;
int i=0;
while((s1 = br.readLine())!=null){
String[] word = s1.split("\\|");
//do something you want
}
}
br.close();
reader.close(); }
至於面試的時候如果讓解釋一下分佈式緩存,我就暈了,不知道什麼好解釋的,估計我就把代碼一列吧,哈哈。