package com.wll.dianxin;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
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;
import java.io.IOException;
class TimeMapper extends Mapper<LongWritable, Text,Text,LongWritable>{
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
String line = value.toString();
if (line.endsWith("03")){
String[] split = line.split("\t");
context.write(new Text(split[0]+"-"+split[2]),new LongWritable(Integer.parseInt(split[4])));
}
}
}
class TimeReducer extends Reducer<Text,LongWritable,Text,LongWritable>{
@Override
protected void reduce(Text key, Iterable<LongWritable> values, Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
long sum=0L;
long count=0L;
for (LongWritable value : values) {
sum+=value.get();
count++;
}
context.write(key,new LongWritable(sum/count));
}
}
public class TimeDemo{
public static void main(String[] args) throws Exception{
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://master:9000");
Job job = Job.getInstance(conf);
job.setJarByClass(TimeDemo.class);
job.setJobName("用户平均停留时长统计案例");
job.setMapperClass(TimeMapper.class);
job.setReducerClass(TimeReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
FileInputFormat.setInputPaths(job,new Path(args[0]));
FileOutputFormat.setOutputPath(job,new Path(args[1]));
boolean b = job.waitForCompletion(true);
if (b){
System.out.println("用户平均停留时长案例mapreduce实现执行成功!>_-");
}else {
System.out.println("用户平均停留时长案例mapreduce实现执行失败");
}
}
}
结果