MapRedece中的分區Partitioner
MapRedece中的分區Partitioner分析
MapReduce中會將map輸出的k-v對,按照相同的key進行分組,然後分發給不同的reduceTask中。
預設的分發規則為:根據key的hashcode%reducetask數來分發
所以如果要按照特定的需求進行分組,則需要改寫資料分發組件Partitioner。
實現
- 自訂資料分發類CustomPartitioner 繼承抽象類別Partitioner
- 重寫getPartition方法
getPartition方法說明
public int getPartition(Text key, LongWritable value, int numPartitions)
- key : map階段輸出的key值
- value : map階段輸出的value值
- numPartitions : 設定的reduce數量(擷取的是job.setNumReduceTasks(int num)設定的num)
- 傳回值是根據自訂規則得出的分區位置
案例需求
根據歸屬地輸出資料流量統計資料結果到不同檔案,以便於在查詢統計結果時可以定位到省級範圍進行流量統計。
實現
/*** 自訂分發規則類CustomPartitioner* @author:yanzhelee*/public class CustomPartitioner extends Partitioner<Text,LongWritable>{ //用於將手機號的前三個數字和分區塊進行對應 static HashMap<String, Integer> provinceMap = new HashMap<String, Integer>(); //設定預設的初始值 static { //key為手機號的前三位元字,value為用於表示地區的分區號 provinceMap.put("135", 0); provinceMap.put("136", 1); provinceMap.put("137", 2); provinceMap.put("138", 3); provinceMap.put("139", 4); } @Override public int getPartition(Text key, FlowBean value, int numPartitions) { Integer code = provinceMap.get(key.toString().substring(0, 3)); //如果不存在,則分區號為5 return code == null ? 5 : code; }}