一:简介

MapReduce主要是先读取文件数据,然后进行Map处理,接着Reduce处理,最后把处理结果写到文件中。

Hadoop MapReduce_hadoop

Hadoop读取数据:通过InputFormat决定读取的数据的类型,然后拆分成一个个InputSplit,每个InputSplit(输入分片)对应一个Map处理,RecordReader读取InputSplit的内容给Map

  • InputFormat:输入格式,决定读取数据的格式,可以是文件或数据库等
  • InputSplit: 输入分片,代表一个个逻辑分片,并没有真正存储数据,只是提供了一个如何将数据分片的方法,通常一个split就是一个block。
  • RecordReader:将InputSplit拆分成一个个<key, value>对给Map处理

  • Mapper:主要是读取InputSplit的每一个Key,Value对并进行处理
  • Shuffle:对Map的结果进行合并、排序等操作并传输到Reduce进行处理
  • Combiner:
  • Reduce:对map进行统计
  1. select:直接分析输入数据,取出需要的字段数据即可
  2. where: 也是对输入数据处理的过程中进行处理,判断是否需要该数据
  3. aggregation: 聚合操作 min, max, sum
  4. group by: 通过Reducer实现
  5. sort:排序
  6. join: map join, reduce join
  • 输出格式: 输出格式会转换最终的键值对并写入文件。默认情况下键和值以tab分割,各记录以换行符分割。输出格式也可以自定义。

二:准备数据

echo "Hadoop Common\nHadoop Distributed File System\nHadoop YARN\nHadoop MapReduce " > /tmp/foobar.txt
hadoop fs -put /tmp/foobar.txt /wordcount/input
hadoop fs -cat /wordcount/input/foobar.txt

Hadoop MapReduce_apache_02

三:Word Count

统计文件中每个单词出现的次数。

  1. 引入依赖
<dependency>                                              
  <groupId>org.apache.hadoop</groupId>                    
  <artifactId>hadoop-common</artifactId>                  
  <version>3.2.1</version>                                
</dependency>                                             
                                                          
<dependency>                                              
  <groupId>org.apache.hadoop</groupId>                    
  <artifactId>hadoop-mapreduce-client-common</artifactId> 
  <version>3.2.1</version>                                
</dependency>                                             
                                                          
<dependency>                                              
  <groupId>org.apache.hadoop</groupId>                    
  <artifactId>hadoop-mapreduce-client-core</artifactId>   
  <version>3.2.1</version>                                
</dependency>
  1. Java
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;

import java.io.IOException;
import java.util.Iterator;
import java.util.StringTokenizer;

public class WordCount {

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        // core-site.xml中配置的fs.defaultFS
        conf.set("fs.defaultFS", "hdfs://localhost:8020");

        Job job = Job.getInstance(conf, "word count");
        job.setJarByClass(WordCount.class);
        job.setMapperClass(WordCount.TokenizerMapper.class);
        job.setReducerClass(WordCount.IntSumReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);


        FileInputFormat.addInputPath(job, new Path("/wordcount/input/foobar.txt"));
        FileOutputFormat.setOutputPath(job, new Path("/wordcount/output"));

        // 等待job完成后退出
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }


    public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
        private static final IntWritable one = new IntWritable(1);
        private Text word = new Text();

        /**
         * map方法会调用多次,每行文本都会调用一次
         * @param key
         * @param value 每一行对应的文本
         * @param context
         */
        @Override
        public void map(Object key, Text value, Mapper<Object, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            StringTokenizer itr = new StringTokenizer(value.toString());

            while(itr.hasMoreTokens()) {
                // 每个单词
                String item = itr.nextToken();
                this.word.set(item);
                context.write(this.word, one);
            }
        }
    }


    public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable result = new IntWritable();

        /**
         * @param key 相同单词归为一组
         * @param values 根据key分组的每一项
         */
        @Override
        public void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            System.out.println(key.toString());
            int sum = 0;

            Iterator iter = values.iterator();
            while (iter.hasNext()) {
                int value = ((IntWritable) iter.next()).get();
                sum += value;
            }

            this.result.set(sum);
            context.write(key, this.result);
        }
    }
}

四:执行.jar

在执行jar文件时需要指定mainClass, 否则会报错 RunJar jarFile [mainClass] args...

方式一:在命令行参数中指定mainClass

指定mainClass类的完全限定名hadoop jar xxx.jar <mainClass类的完全限定名>

mvn clean package
hadoop jar target/hadoop-mapreduce-wordcount-1.0-SNAPSHOT.jar org.example.WordCount
方式二:使用maven插件指定mainClass

配置maven-jar-plugin插件, 在插件中指定mainClass,在插件中配置了mainClass在命令行中就不需要再指定mainClass了。

<build>
	<plugins>
	  <plugin>
	    <groupId>org.apache.maven.plugins</groupId>
	    <artifactId>maven-jar-plugin</artifactId>
	    <configuration>
	      <archive>
	        <manifest>
	          <addClasspath>true</addClasspath>
	          <classpathPrefix></classpathPrefix>
	          <mainClass>org.example.WordCount</mainClass>
	        </manifest>
	      </archive>
	    </configuration>
	  </plugin>
	</plugins>
</build>

Hadoop MapReduce_hadoop_03

mvn clean package
hadoop jar target/hadoop-mapreduce-wordcount-1.0-SNAPSHOT.jar

Hadoop MapReduce_Text_04

Hadoop MapReduce_Text_05