大数据场景下的Java:Hadoop MapReduce实战示例

原创 雨点打透心脏的1/2处 2024-09-25 06:42 183阅读 0赞

在大数据场景下,Java语言配合Apache Hadoop的MapReduce框架,可以实现大规模数据的处理和分析。

以下是一个简单的MapReduce实战示例,我们将计算一个文本文件中每个单词出现的次数:

  1. 创建Mapper类:将文件中的每一行转化为键值对,其中键是单词,值为1。
  1. import java.io.IOException;
  2. import org.apache.hadoop.io.IntWritable;
  3. import org.apache.hadoop.io.Text;
  4. import org.apache.hadoop.mapreduce.Mapper;
  5. public class WordCountMapper extends Mapper<Object, Text, Text, IntWritable>> {
  6. private final static IntWritable one = new IntWritable(1);
  7. private Text word = new Text();
  8. @Override
  9. protected void map(Object key, Text value,
  10. Context context) throws IOException, InterruptedException {
  11. // Split the text into words
  12. String[] words = value.toString().split("\\s+");
  13. // For each word, emit a key-value pair
  14. for (String wordElement : words) {
  15. word.set(wordElement);
  16. context.write(word, one);
  17. }
  18. }
  19. }
  1. 创建Reducer类:将Map阶段生成的键值对进行聚合,这里的聚合方式是将同一个单词的所有出现次数相加。
  1. import java.io.IOException;
  2. import org.apache.hadoop.io.IntWritable;
  3. import org.apache.hadoop.mapreduce.Reducer;
  4. public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable>> {
  5. private IntWritable count = new IntWritable();
  6. @Override
  7. protected void reduce(Text key, Iterable<IntWritable> values,
  8. Context context) throws IOException, InterruptedException {
  9. // Sum up the occurrences of this word
  10. int sum = 0;
  11. for (IntWritable value : values) {
  12. sum += value.get();
  13. }
  14. // Emit the word and its count
  15. count.set(sum);
  16. context.write(key, count);
  17. }
  18. }
  1. 编写Hadoop Job配置文件:定义MapReduce作业的基本信息,包括输入和输出路径。
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <jobConf>
  3. <property>
  4. <name>mapreduce.input.path</name>
  5. <value>/path/to/your/textfile</value>
  6. </property>
  7. <property>
  8. <name>mapreduce.output.keytab.file</name>
  9. <value>/path/to/your/keytab/file</value>
  10. </property>
  11. <property>
  12. <name>mapreduce.output.textfile</name>
  13. <value>/path/to/output/textfile</value>
  14. </property>
  15. <!-- Use YARN as the resource manager -->
  16. <property>
  17. <name>hadoop.jobtracker.address</name>
  18. <value>yarn.nodemanager.address</value>
  19. </property>
  20. <!-- Specify the number of map tasks and reduce tasks -->
  21. <property>
  22. <name>mapreduce.num.mappers</name>
  23. <value>1000</value>
  24. </property>
  25. <property>
  26. <name>mapreduce.num.reducers</name>
  27. <value>1</value>
  28. </property>
  29. </jobConf>
  1. 运行MapReduce作业:在Hadoop集群中,使用hadoop jar命令来执行你的MapReduce程序。

例如:

  1. hadoop jar hadoop-mapreduce-tools.jar job -config /path/to/your/jobconf.xml /path/to/your/inputfile

这段命令会执行一个名为job的MapReduce作业,配置文件是jobconf.xml,输入文件是inputfile

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,183人围观)

还没有评论,来说两句吧...

相关阅读