Mapper Reducer计算每日的访客量JAVA代码
时间: 2024-10-22 17:05:08 浏览: 15
在Hadoop MapReduce框架下,想要计算每天的访客量,通常涉及到三个步骤:Map阶段、Shuffle阶段和Reduce阶段。这里是一个简单的Java示例:
```java
import java.io.IOException;
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.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class VisitorCount {
static class VisitMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String[] fields = value.toString().split(",");
word.set(fields[0]); // 假设日期字段是第一个
context.write(word, one);
}
}
static class VisitReducer 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);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "visitor count");
job.setJarByClass(VisitorCount.class);
job.setMapperClass(VisitMapper.class);
job.setCombinerClass(VisitReducer.class);
job.setReducerClass(VisitReducer.class);
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);
}
}
```
在这个例子中,`VisitMapper`将每个访问记录解析为日期和一条访问,然后生成键值对(日期,1)。`VisitReducer`会累加每日的访问次数,并将结果保存到指定的输出路径。
阅读全文