Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Hadoop WordCount 從編譯到執行的完整命令列流程

現在用 Eclipse 開發 Hadoop 程式很方便,但對小型程式的驗證來說,命令列反而更直接。以下是初學 Hadoop 時留下的操作筆記。

1. WordCount.java

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

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class WordCount extends Configured implements Tool {

    public static class MapClass extends MapReduceBase
            implements Mapper<LongWritable, Text, Text, IntWritable> {

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

        public void map(LongWritable key, Text value,
                        OutputCollector<Text, IntWritable> output, Reporter reporter)
                throws IOException {
            String line = value.toString();
            StringTokenizer itr = new StringTokenizer(line);
            while (itr.hasMoreTokens()) {
                word.set(itr.nextToken());
                output.collect(word, one);
            }
        }
    }

    /** Reducer:把同一 key 的值累加 */
    public static class Reduce extends MapReduceBase
            implements Reducer<Text, IntWritable, Text, IntWritable> {

        public void reduce(Text key, Iterator<IntWritable> values,
                           OutputCollector<Text, IntWritable> output, Reporter reporter)
                throws IOException {
            int sum = 0;
            while (values.hasNext()) {
                sum += values.next().get();
            }
            output.collect(key, new IntWritable(sum));
        }
    }

    static int printUsage() {
        System.out.println("wordcount [-m <maps>] [-r <reduces>] <input> <output>");
        ToolRunner.printGenericCommandUsage(System.out);
        return -1;
    }

    public int run(String[] args) throws Exception {
        JobConf conf = new JobConf(getConf(), WordCount.class);
        conf.setJobName("wordcount");

        conf.setOutputKeyClass(Text.class);       // key 是單字
        conf.setOutputValueClass(IntWritable.class);  // value 是次數

        conf.setMapperClass(MapClass.class);
        conf.setCombinerClass(Reduce.class);
        conf.setReducerClass(Reduce.class);

        List<String> other_args = new ArrayList<String>();
        for (int i = 0; i < args.length; ++i) {
            try {
                if ("-m".equals(args[i])) {
                    conf.setNumMapTasks(Integer.parseInt(args[++i]));
                } else if ("-r".equals(args[i])) {
                    conf.setNumReduceTasks(Integer.parseInt(args[++i]));
                } else {
                    other_args.add(args[i]);
                }
            } catch (NumberFormatException except) {
                System.out.println("ERROR: Integer expected instead of " + args[i]);
                return printUsage();
            } catch (ArrayIndexOutOfBoundsException except) {
                System.out.println("ERROR: Required parameter missing from " + args[i - 1]);
                return printUsage();
            }
        }

        // 必須剛好剩下兩個參數
        if (other_args.size() != 2) {
            System.out.println("ERROR: Wrong number of parameters: "
                    + other_args.size() + " instead of 2.");
            return printUsage();
        }
        FileInputFormat.setInputPaths(conf, other_args.get(0));
        FileOutputFormat.setOutputPath(conf, new Path(other_args.get(1)));

        JobClient.runJob(conf);
        return 0;
    }

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new WordCount(), args);
        System.exit(res);
    }
}

2. 編譯

先確認 Hadoop 集群(單機模式也可以)已設定完成,建立工作目錄後編譯:

javac -classpath /home/admin/hadoop/hadoop-0.19.1-core.jar WordCount.java \
      -d /home/admin/WordCount

3. 打包成 jar

編譯後目錄下會產生 WordCount.class、WordCount$Map.class、WordCount$Reduce.class 三個檔案:

cd /home/admin/WordCount
jar cvf WordCount.jar *.class

4. 準備輸入資料

[admin@host WordCount]$ cat input1.txt
Hello, i love china
are you ok?
[admin@host WordCount]$ cat input2.txt
hello, i love word
You are ok

在 HDFS 上建立目錄並上傳:

hadoop fs -mkdir /tmp/input
hadoop fs -mkdir /tmp/output
hadoop fs -put input1.txt /tmp/input/
hadoop fs -put input2.txt /tmp/input/

5. 執行

[admin@host WordCount]$ hadoop jar WordCount.jar WordCount /tmp/input /tmp/output
10/09/16 22:49:43 INFO mapred.FileInputFormat: Total input paths to process : 2
10/09/16 22:49:43 INFO mapred.JobClient: Running job: job_201008171228_76165
10/09/16 22:49:44 INFO mapred.JobClient: map 0% reduce 0%
10/09/16 22:49:47 INFO mapred.JobClient: map 100% reduce 0%
10/09/16 22:49:54 INFO mapred.JobClient: map 100% reduce 100%
10/09/16 22:49:55 INFO mapred.JobClient: Job complete: job_201008171228_76165
10/09/16 22:49:55 INFO mapred.JobClient: Launched map tasks=2
10/09/16 22:49:55 INFO mapred.JobClient: Reduce input groups=11
10/09/16 22:49:55 INFO mapred.JobClient: Map input records=4
10/09/16 22:49:55 INFO mapred.JobClient: Reduce output records=11

6. 查看結果

[admin@host WordCount]$ hadoop fs -ls /tmp/output/
Found 2 items
drwxr-x--- - admin admin    0 2010-09-16 22:43 /tmp/output/_logs
-rw-r----- 1 admin admin  102 2010-09-16 22:44 /tmp/output/part-00000

[admin@host WordCount]$ hadoop fs -cat /tmp/output/part-00000
Hello, 1
You 1
are 2
china 1
hello, 1
i 2
love 2
ok 1
ok? 1
word 1
you 1

可以看到 MapReduce 的 Spliterator 特性在此顯現:大小寫不同的 Hello 與 hello 被視為不同 key,而標點也沒有被剝離,所以 ok 與 ok? 分開計數。若要更乾淨的統計,需要在 Map 階段自行正規化。

Copyright © Linux教程網 All Rights Reserved