MapReduce是一种编程模型,用于处理和生成大数据集,在Java中,可以使用Hadoop的MapReduce API来实现MapReduce程序,以下是一个简单的MapReduce Java例子,包括Map和Reduce两个阶段。
1. Map阶段
Map阶段的输入数据是一组键值对,输出是一组中间键值对,Map函数的实现需要继承Mapper
类并重写map
方法。
import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] words = value.toString().split("\s+"); for (String w : words) { word.set(w); context.write(word, one); } } }
2. Reduce阶段
Reduce阶段的输入是一组具有相同键的值,输出是一组最终的键值对,Reduce函数的实现需要继承Reducer
类并重写reduce
方法。
import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> { @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable value : values) { sum += value.get(); } context.write(key, new IntWritable(sum)); } }
3. Driver类
Driver类负责配置和启动MapReduce作业。
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 WordCount { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(WordCountMapper.class); job.setCombinerClass(WordCountReducer.class); job.setReducerClass(WordCountReducer.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); } }
这个例子是一个单词计数程序,它统计输入文本中每个单词出现的次数,在Map阶段,它将输入文本拆分为单词,并为每个单词生成一个键值对(单词,1),在Reduce阶段,它将所有具有相同键的值相加,得到每个单词的总计数,Driver类配置和启动MapReduce作业。
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/832842.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复