Hadoop 单词计数器

Hadoop 单词计数器

Tags: Hadoop

摘要

Hadoop 单词计数器

概述

输入参数是两个文件,使用Hadoop统计两个文件中每个单词出现的次数。这就是单词计数器。
传统代码和新api没有什么本质的区别,效果是一样的。可以只看一个。
注意打包是想更改main类,需要修改pom.xml中的mainClass。
(build->plugins->configuration->archive->manifest->mainClass)

通过maven打包之后指定了main方法所在的类。而且把所有的依赖jar都引用进来。
所以执行hadoop jar命令是也比较方便。

hadoop jar xxxx.jar input output

单词计数器代码

package hadoop.day01;

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.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 计数器
 */
public class WordCount_001 {

    private static final Logger log = LoggerFactory.getLogger(WordCount_001.class);

    public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

        @Override
        public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, Reporter reporter) throws IOException {

            String line = value.toString();
            StringTokenizer tokenizer = new StringTokenizer(line);
            while (tokenizer.hasMoreTokens()) {
                word.set(tokenizer.nextToken());
                output.collect(word, one);
            }

        }

    }


    public static class Reduce extends MapReduceBase implements Reducer<Text, IntWritable, Text, IntWritable> {
        @Override
        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));
        }
    }


    public static void main(String[] args) throws Exception {
        log.info("begin ...");
        JobConf conf = new JobConf(WordCount_001.class);
        conf.setJobName("wordcount");

        conf.setOutputKeyClass(Text.class);
        conf.setOutputValueClass(IntWritable.class);

        conf.setMapperClass(Map.class);
        conf.setReducerClass(Reduce.class);


        conf.setOutputFormat(TextOutputFormat.class);
        FileInputFormat.setInputPaths(conf, new Path(args[0]));
        FileOutputFormat.setOutputPath(conf, new Path(args[1]));

        JobClient.runJob(conf);
    }

}

单词计数器代码-新API

package hadoop.day01;


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.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.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

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

public class WordCount extends Configured implements Tool {

    public static class WordCountMap extends
            Mapper<LongWritable, Text, Text, IntWritable> {

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

        public void map(LongWritable key, Text value, Mapper.Context context)
                throws IOException, InterruptedException {
            String line = value.toString();
            StringTokenizer token = new StringTokenizer(line);
            while (token.hasMoreTokens()) {
                word.set(token.nextToken());
                context.write(word, one);
            }
        }
    }

    public static class WordCountReduce extends
            Reducer<Text, IntWritable, Text, IntWritable> {

        public void reduce(Text key, Iterable<IntWritable> values,
                           Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            context.write(key, new IntWritable(sum));
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Job job = new Job(getConf());
        job.setJarByClass(WordCount.class);
        job.setJobName("wordcount");

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        job.setMapperClass(WordCountMap.class);
        job.setReducerClass(WordCountReduce.class);

        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        return (job.waitForCompletion(true) ? 0 : -1);
    }

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


}

实验步骤

准备输入文件
/root/file01
hello world by world
/root/file02
hello hadoop goodbye hadoop

新建输入参数文件所在目录
hadoop fs -mkdir input

上传文件
hadoop fs -put file01 input/file01
hadoop fs -put file02 input/file02

打包jar
cd 开发目录 ,比如 M:\coding_test_proj\test_hadoop
执行打包命令 mvn package

生成可执行jar
位置:target/hadoop-1.0-SNAPSHOT.jar

上传jar到hadoop所在的环境下。

执行jar
hadoop jar hadoop-1.0-SNAPSHOT.jar input output

root@master:~# hadoop jar hadoop-1.0-SNAPSHOT.jar input output
15/11/08 22:06:45 INFO input.FileInputFormat: Total input paths to process : 2
15/11/08 22:06:45 INFO util.NativeCodeLoader: Loaded the native-hadoop library
15/11/08 22:06:45 WARN snappy.LoadSnappy: Snappy native library not loaded
15/11/08 22:06:45 INFO mapred.JobClient: Running job: job_201511060514_0007
15/11/08 22:06:46 INFO mapred.JobClient:  map 0% reduce 0%
15/11/08 22:06:57 INFO mapred.JobClient:  map 100% reduce 0%
15/11/08 22:07:06 INFO mapred.JobClient:  map 100% reduce 100%
15/11/08 22:07:10 INFO mapred.JobClient: Job complete: job_201511060514_0007
15/11/08 22:07:10 INFO mapred.JobClient: Counters: 29
15/11/08 22:07:10 INFO mapred.JobClient:   Job Counters 
15/11/08 22:07:10 INFO mapred.JobClient:     Launched reduce tasks=1
15/11/08 22:07:10 INFO mapred.JobClient:     SLOTS_MILLIS_MAPS=12534
15/11/08 22:07:10 INFO mapred.JobClient:     Total time spent by all reduces waiting after reserving slots (ms)=0
15/11/08 22:07:10 INFO mapred.JobClient:     Total time spent by all maps waiting after reserving slots (ms)=0
15/11/08 22:07:10 INFO mapred.JobClient:     Launched map tasks=2
15/11/08 22:07:10 INFO mapred.JobClient:     Data-local map tasks=2
15/11/08 22:07:10 INFO mapred.JobClient:     SLOTS_MILLIS_REDUCES=8466
15/11/08 22:07:10 INFO mapred.JobClient:   File Output Format Counters 
15/11/08 22:07:10 INFO mapred.JobClient:     Bytes Written=40
15/11/08 22:07:10 INFO mapred.JobClient:   FileSystemCounters
15/11/08 22:07:10 INFO mapred.JobClient:     FILE_BYTES_READ=103
15/11/08 22:07:10 INFO mapred.JobClient:     HDFS_BYTES_READ=285
15/11/08 22:07:10 INFO mapred.JobClient:     FILE_BYTES_WRITTEN=154576
15/11/08 22:07:10 INFO mapred.JobClient:     HDFS_BYTES_WRITTEN=40
15/11/08 22:07:10 INFO mapred.JobClient:   File Input Format Counters 
15/11/08 22:07:10 INFO mapred.JobClient:     Bytes Read=49
15/11/08 22:07:10 INFO mapred.JobClient:   Map-Reduce Framework
15/11/08 22:07:10 INFO mapred.JobClient:     Map output materialized bytes=109
15/11/08 22:07:10 INFO mapred.JobClient:     Map input records=2
15/11/08 22:07:10 INFO mapred.JobClient:     Reduce shuffle bytes=109
15/11/08 22:07:10 INFO mapred.JobClient:     Spilled Records=16
15/11/08 22:07:10 INFO mapred.JobClient:     Map output bytes=81
15/11/08 22:07:10 INFO mapred.JobClient:     Total committed heap usage (bytes)=336928768
15/11/08 22:07:10 INFO mapred.JobClient:     CPU time spent (ms)=560
15/11/08 22:07:10 INFO mapred.JobClient:     Combine input records=0
15/11/08 22:07:10 INFO mapred.JobClient:     SPLIT_RAW_BYTES=236
15/11/08 22:07:10 INFO mapred.JobClient:     Reduce input records=8
15/11/08 22:07:10 INFO mapred.JobClient:     Reduce input groups=5
15/11/08 22:07:10 INFO mapred.JobClient:     Combine output records=0
15/11/08 22:07:10 INFO mapred.JobClient:     Physical memory (bytes) snapshot=342085632
15/11/08 22:07:10 INFO mapred.JobClient:     Reduce output records=5
15/11/08 22:07:10 INFO mapred.JobClient:     Virtual memory (bytes) snapshot=1155170304
15/11/08 22:07:10 INFO mapred.JobClient:     Map output records=8

查看输出结果

hadoop fs -ls output

下载结果文件
hadoop fs -get output/part-r-00000 part-r-00000
文件被下载到 /root/part-r-00000

重复执行hadoop jar会提示 Output directory output already exists
删除output命令是
hadoop fs -rmr output

完整代码地址
https://coding.net/u/javacore/p/test_hadoop/git