public class lihongbo {
public lihongbo() {}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(); // 创建一个对象,用于读取配置文件
String[] otherArgs = (new GenericOptionsParser(conf, args)).getRemainingArgs();
// 获取命令行中除了配置文件以外的其他参数
if(otherArgs.length < 2) {
System.err.println("Usage: wordcount <in> [<in>...] <out>");
System.exit(2);
}
// 如果参数不足两个,则输出用法提示并退出程序
Job job = Job.getInstance(conf, "word count"); // 创建一个作业对象
job.setJarByClass(lihongbo.class); // 设置作业运行时使用的 JAR 文件
job.setMapperClass(lihongbo.TokenizerMapper.class); // 设置 Mapper 类
job.setCombinerClass(lihongbo.IntSumReducer.class); // 设置 Combiner 类(可选)
job.setReducerClass(lihongbo.IntSumReducer.class); // 设置 Reducer 类
job.setOutputKeyClass(Text.class); // 设置输出键类型
job.setOutputValueClass(IntWritable.class); // 设置输出值类型
for(int i = 0; i < otherArgs.length - 1; ++i) {
FileInputFormat.addInputPath(job, new Path(otherArgs[i])); // 添加输入路径
}
FileOutputFormat.setOutputPath(job, new Path(otherArgs[otherArgs.length - 1])); // 设置输出路径
System.exit(job.waitForCompletion(true) ? 0 : 1); // 启动作业并等待其完成,返回状态码 0 表示成功,1 表示失败
}
public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
// 定义一个 Mapper 类,继承自 Mapper<Object, Text, Text, IntWritable>
private static final IntWritable one = new IntWritable(1); // 定义一个常量 one,值为 1
private Text word = new Text(); // 定义一个文本类型变量 word
public TokenizerMapper() {
// 构造函数,没有实际操作
}
public void map(Object key, Text value, Mapper<Object, Text, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
// 实现 Mapper 类中的 map 函数,对输入数据进行处理
StringTokenizer itr = new StringTokenizer(value.toString()); // 将输入数据转化为字符串
while(itr.hasMoreTokens()) { // 如果还有单词可以读取
this.word.set(itr.nextToken()); // 获取下一个单词
context.write(this.word, one); // 输出键值对,键为单词,值为 one
}
}
}
public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
// 定义一个 Reducer 类,继承自 Reducer<Text, IntWritable, Text, IntWritable>
private IntWritable result = new IntWritable(); // 定义一个整数类型变量 result,用于保存累加结果
public IntSumReducer() {
// 构造函数,没有实际操作
}
public void reduce(Text key, Iterable<IntWritable> values,
Reducer<Text, IntWritable, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
// 实现 Reducer 类中的 reduce 函数,对经过 Mapper 处理后的数据进行汇总
int sum = 0; // 定义一个整数变量 sum,用于保存累加结果
for(IntWritable val : values) { // 遍历键值对列表
sum += val.get(); // 累加键值对的值
}
this.result.set(sum); // 将累加的结果设置为 result 的值
context.write(key, this.result); // 输出