MapReduce 允许用户编写程序来定义计数器,计数器的值可在 mapper 或 reduce 中增加,计数器由一个 Java 枚举(enum)类型来定义,以便对有关的计数器分组,一个作业可以定义的枚举类型数量不像,各个枚举类型所包含的字段也不限。枚举类型的名称即为组的名称,枚举类型的字段是计数器的名称。
计数器是全局的,换言之,MapReduce 框架将跨所有 map 和 reduce 聚集这些计数器,并在作业结束时产生一个最终结果。
示例:
在 wordcount 添加计数器来记录所有 长度小于5(SHORT_WORD)和长度大于10 (LONG_WORD)的单词
public class wordcount extends Configured implements Tool {
enum MyCounter {
LONG_WORD, // 长度小于5
SHORT_WORD // 长度大于10
}
public static class TokenizerMapper
extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
if (word.getLength() < 5) {
context.getCounter(MyCounter.SHORT_WORD).increment(1);
} else if (word.getLength() > 10){
context.getCounter(MyCounter.LONG_WORD).increment(1);
}
context.write(word, one);
}
}
}
public static class IntSumReducer
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);
}
}
@Override
public int run(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Usage: wordcount <in> [<in>...] <out>");
System.exit(2);
}
Job job = Job.getInstance(this.getConf(), "word count");
job.setJarByClass(wordcount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
for (int i = 0; i < args.length - 1; ++i) {
FileInputFormat.addInputPath(job, new Path(args[i]));
}
FileOutputFormat.setOutputPath(job,
new Path(args[args.length - 1]));
return job.waitForCompletion(true) ? 0 : 1;
}
public static void main(String[] args) throws Exception {
int code = ToolRunner.run(new wordcount(), args);
System.exit(code);
}
}
当程序执行完后,会输出自定义的 计数器值