问题一.统计页面浏览量
Map阶段,对于每一条数据,设置一个默认键(只用于标记该行),值设置为1。Reduce阶段,获得所有的值的和即可。
总体思路:
1.Mapper阶段:P1Mapper 对每一行输入数据输出键值对 (“line”, 1)。
2.Shuffle和Sort阶段:框架会自动将具有相同键的值聚集到一起。
3.Reducer阶段:P1Reducer 接收键 (“line”) 和所有的 1,并将这些值累加,最终输出键值对 (“line”, 总行数)
Mapper
package mr1;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class P1Mapper extends Mapper<LongWritable, Text, Text, IntWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
context.write(new Text("line"), new IntWritable(1));
}
}
extends Mapper<LongWritable, Text, Text, IntWritable>:表明这个类继承了 Mapper 类,其中泛型参数指定了输入和输出类型:
输入键类型:LongWritable(每行文本的偏移量)。
输入值类型:Text(一行文本内容)。
输出键类型:Text(这里用作标记字符串 "line")。
输出值类型:IntWritable(这里用作计数,值为1)
Reducer
package mr1;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class P1Reducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
@Override
protected 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);
}
}
P1Reducer extends Reducer<Text, IntWritable, Text, IntWritable>:表明这个类继承了 Reducer 类,其中泛型参数指定了输入和输出类型:
输入键类型:Text(Mapper输出的键)。
输入值类型:IntWritable(Mapper输出的值)。
输出键类型:Text(Reducer的输出键)。
输出值类型:IntWritable(Reducer的输出值)。
Reduce方法重写父类:
protected void reduce(Text key, Iterable<IntWritable> values, Context context):
key:输入键,来自Mapper的输出键。
values:输入值的可迭代集合,包含所有与该键相关的值。
context:MapReduce框架提供的上下文对象,用于与框架进行交互,输出键值对等。
Driver
package mr1;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class P1Driver {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: PageViewDriver <input path> <output path>");
System.exit(-1);
}
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "Page View Count");
job.setJarByClass(P1Driver.class);//设置作业的Jar包
job.setMapperClass(P1Mapper.class);
job.setCombinerClass(P1Reducer.class);
job.setReducerClass(P1Reducer.class);//设置Combiner类
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}