大数据系列:hadoop 入门(hello world 版)
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;
public class DriverWordCount {
/******************************************map stage********************************************************/
public static class WCMap extends Mapper<LongWritable, Text,Text,LongWritable>{
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] words=value.toString().split(",");
for (String vocabulary : words) {
Text k2=new Text(vocabulary);
LongWritable v2=new LongWritable(1L);
context.write(k2,v2);
}
}
}
/******************************************shuffle*****************reduce stage********************************************************/
/******************************************分区分组 相同的key 会进入到同一个reduce中********************************************************/
public static class WC_Reduce extends Reducer<Text,LongWritable,Text,LongWritable>{
@Override
protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
long sum=0;
for (LongWritable value : values) {
sum+=value.get();
}
context.write(key,new LongWritable(sum));
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
// MapReduce 分为两个部分 第一部分map 第二部 reduce
Configuration configuration = new Configuration();
Job job = Job.getInstance(configuration, DriverWordCount.class.getSimpleName());
job.setJarByClass(DriverWordCount.class);
FileInputFormat.addInputPath(job,new Path(args[0]));
job.setMapperClass(WCMap.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);
job.setReducerClass(WC_Reduce.class);
job.setMapOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
FileOutputFormat.setOutputPath(job,new Path(args[1]));
job.waitForCompletion(true);
}
}
运行 hadoop jar hadoop-1.0-SNAPSHOT.jar DriverWordCount /software/dianxin_data.csv /out2
posted on 2019-07-12 17:06 Indian_Mysore 阅读(159) 评论(1) 编辑 收藏 举报