共計(jì) 1494 個(gè)字符,預(yù)計(jì)需要花費(fèi) 4 分鐘才能閱讀完成。
編寫 MapReduce 程序的基本步驟如下:
- 創(chuàng)建一個(gè)實(shí)現(xiàn)了 Mapper 接口的類,重寫 map 方法。map 方法接收一個(gè)鍵值對(duì)作為輸入,將輸入數(shù)據(jù)處理并輸出為中間鍵值對(duì)。
public class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable> {private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {word.set(tokenizer.nextToken());
context.write(word, one);
}
}
}
- 創(chuàng)建一個(gè)實(shí)現(xiàn)了 Reducer 接口的類,重寫 reduce 方法。reduce 方法接收中間鍵值對(duì)作為輸入,將輸入數(shù)據(jù)根據(jù)鍵匯總并輸出為最終結(jié)果鍵值對(duì)。
public class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> {private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {int sum = 0;
for (IntWritable val : values) {sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
- 創(chuàng)建一個(gè)配置對(duì)象,設(shè)置 MapReduce 作業(yè)的相關(guān)參數(shù)。
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
- 指定輸入數(shù)據(jù)的路徑和輸出結(jié)果的路徑。
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
- 設(shè)置 Mapper 和 Reducer 的類。
job.setMapperClass(MyMapper.class);
job.setCombinerClass(MyReducer.class);
job.setReducerClass(MyReducer.class);
- 設(shè)置最終結(jié)果的鍵值對(duì)類型。
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
- 提交 MapReduce 作業(yè)。
System.exit(job.waitForCompletion(true) ? 0 : 1);
以上就是編寫 MapReduce 程序的基本步驟。根據(jù)具體需求,可以對(duì) Mapper 和 Reducer 的邏輯進(jìn)行擴(kuò)展和修改。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完