► 當有些情況需要一個 map 直接處理完一個完整檔案時(不讓系統進行分割分散處理), 一般作法有兩種
1. 設定參數 mapred.min.split.size 讓其等同文件大小. (簡單,但這不是好方法)
2. 覆寫 FileInputFormat.isSplitable() 傳回值為 false , 然後 job.setInputFormatClass(MaxInputFormat.class) 即可
►若需要 整個檔案內容作一筆一次 來處理, 則除需要 isSplitable() 傳回值為 false 外, 另需要變更 RecordReader 的行為模式, 然後改以自訂的RecordReader類別來處理.
InputFormat
1. 設定參數 mapred.min.split.size 讓其等同文件大小. (簡單,但這不是好方法)
2. 覆寫 FileInputFormat.isSplitable() 傳回值為 false , 然後 job.setInputFormatClass(MaxInputFormat.class) 即可
public class MaxInputFormat extends FileInputFormat<LongWritable, Text> { @Override protected boolean isSplitable(JobContext context, Path filename) { return false; } }
►若需要 整個檔案內容作一筆一次 來處理, 則除需要 isSplitable() 傳回值為 false 外, 另需要變更 RecordReader 的行為模式, 然後改以自訂的RecordReader類別來處理.
InputFormat
自訂讀入行為 AllDataRecordReaderpublic class MaxInputFormat extends FileInputFormat<LongWritable, Text> { @Override protected boolean isSplitable(JobContext context, Path filename) { return false; } @Override //因想要一次讀入全部資料, 故需替換為自訂讀取類別 public RecordReader<LongWritable, Text> createRecordReader(InputSplit split, TaskAttemptContext context) throws IOException,InterruptedException { return new AllDataRecordReader(); } }
至於 RecordReader<LongWritable, Text> 亦可改為 RecordReader<NullWritable, BytesWritable> 型態以 Bytes 進行資料傳遞,也無需key值. 畢竟一次傳完所有資料有無key都一樣. 若使用 BytesWritable 沒有特別的輸出處理則輸出資料為 31 39 35 30 2d 31 32 2d 30 34 20 37 39 39 十六進制值public class AllDataRecordReader extends RecordReader<LongWritable, Text> { private FileSplit fileSplit; private Configuration conf; private Text value = new Text(); private boolean processed = false; @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException { this.fileSplit = (FileSplit) split; this.conf = context.getConfiguration(); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { if (!processed) { byte[] contents = new byte[(int) fileSplit.getLength()]; Path file = fileSplit.getPath(); FileSystem fs = file.getFileSystem(conf); FSDataInputStream in = null; try { in = fs.open(file); IOUtils.readFully(in, contents, 0, contents.length);//一次讀入全部資料 value.set(contents, 0, contents.length); } finally { IOUtils.closeStream(in); } processed = true; return true; } return false; } @Override public LongWritable getCurrentKey() throws IOException, InterruptedException { return new LongWritable(0); } @Override public Text getCurrentValue() throws IOException,InterruptedException { return value; } @Override public float getProgress() throws IOException { return processed ? 1.0f : 0.0f; } @Override public void close() throws IOException { } }