First, preface
We have already built the hadoop2.x development environment under the CenOS6.5. Now that the environment has been set up, then we should do something about it! Like a HelloWorld in the Hadoop World, the WordCount program (a simple word counting program)
Second, the operation of the official case of WordCount
2.1 Program Introduction
The WordCount program is a case of Hadoop, and we can find the jar file containing the program in the Hadoop directory (Hadoop-mapreduce-examples-2.7.1.jar), where the path is hadoop/ Share/hadoop/mapreduce.
We can use the hadoop jar command to view the jar package details. Execute command:Hadoop jar Hadoop-mapreduce-examples-2.7.1.jar
As you can see, there is not a single case in the jar file, but of course we just want to see the WordCount program and the other side edges. Then we follow the prompts, execute the command:hadoop jar Hadoop-mapreduce-examples-2.7.1.jar WordCount See what's in there?
At the prompt, it says it needs to input files and output directories, then we will prepare the following input files and output directories.
注:其实只需要准备输入文件,不需要准备输入目录。因为 MapReduce 程序的运行,其输入目录不能是已存在的,否则会抛出异常。这是为了避免数据覆盖的问题。请看《Hadoop权威指南》
2.2 Preparation Materials
In order to facilitate the use of the official JAR file, we create an input directory under the current directory (you can also create a directory under another directory, the directory name can be taken, like good), to store the import file. Then prepare 2 input files. As shown below:
Since we are using the HDFs file system, we need to put the file into HDFs if we want to run WordCount this MapReduce program. So we use the HDFs File System command to create an input directory under the HDFs file system root, which is used to save the entry file. Execute command:hadoop fs-mkdir/input
注:hadoop fs -mkdir 命令是用来在 HDFS 上创建目录的,类似于Linux下的 mkdir 命令
Once the catalog is created, we need to copy the input files that have just been prepared on the local file system to HDFS. Execute command:hadoop fs-put input/f*.txt/input
2.3 Running the program
Get ready to work, then start running the program now. Execute command:hadoop jar Hadoop-mapreduce-examples-2.7.1.jar wordcount/input/output
注:hadoop jar hadoop-mapreduce-examples-2.7.1.jar wordcount /input /output详解- 该命令中 /input 表示使用 HDFS 上根目录(/)下的 input 目录下所有文件作为程序输入- /output 表示使用 HDFS 根目录下的 output 目录存储程序的输出(该 output 文件,是本来不存在的,会由程序自动创建)
From the terminal you can see the following command output:
After the program runs, let's see what the output is, execute the command:Hadoop fs-cat/output/*
注:hadoop fs -cat 命令功能类似于linux下的 cat 命令
From the above output, you can see the program will be in our input files in the occurrence of words, statistics. It's all in the form of Key,value.
Three, the WordCount official procedure source code Analysis
3.1 View Source
has just run the WordCount program a cool, now we look at the source code to see the true colors of the program.
We use Eclipse to view the source code. In the directory where the Hadoop-mapreduce-examples-2.7.1.jar file is located, there is a source directory where the jar corresponds to the Hadoop-mapreduce-examples-2.7.1-sources.jar. The following scenarios are viewed through Eclipse:
You can see that the program is simple and has very little code. It contains 2 internal classes, each inheriting the word Mapper and the Reducer class. This is actually the work we need to do when writing a MapReduce program.
3.2 Analysis Program Structure
The approximate structure of the program is as follows: (Here's just a quick, detailed code comment in the self-implemented WordCount)
①mapper Zone: Inherits from an inner class of the Mapper class, implementing the Map () function
②reducer Zone: Inherits from an inner class of the Reducer class, implementing the reduce () function
③client District: Program Operation entrance
This structure, which is the basic structure of the MapReduce program, is written. To write a MapReduce program, our program apes only need to implement the map () and reduce () programs.
3.3 Self-implemented WordCount
We implement a WordCount program of our own according to the preparation of the MapReduce program.
① Creating a Java Project
② Import the following jar package
注:其中 hadoop-hdfs-2.7.1.jar 和 hadoop-mapreduce-client-core-2.7.1.jar 是编写程序需要的 jar 包,其他的 jar 包是我们在 linux 下运行程序需要的依赖 jar,也就是环境需要的 jar 包。
③ Writing Program: Wordcount.java
Import Java.io.ioexception;import Java.util.stringtokenizer;import Org.apache.hadoop.conf.configuration;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.output.fileoutputformat;/** * Wordcount:mapreduce Primary case, press stereotyped writing structure to write all the time * @author Johnnie * /public class WordCount {/** * Mapper zone: WordCount program Map class * Mapper<keyin, Valuein, Keyout, Valueout>: * | | | | * Input key type input value type output key type output value type * @author Johnnie * */public static class Tokenizermapper ext Ends Mapper<longwritable, text, text, intwritable>{//output private Text Word = new text (); KEyout//Because if each word appears, it is set to 1 and as a <key,value> pair, so it can be declared as a constant with a value of 1 private final static intwritable one = NE W intwritable (1); Valueout/** * value is the value of each line of text * context is a contextual object */@Override public void M AP (longwritable key, Text value, Context context) throws IOException, Interruptedexception {//Gets the value of each row of data String Linevalue = value.tostring (); Participle: Splits the words of each line and splits them according to "\t\n\r\f" (Spaces, tabs, line feeds, carriage returns, page breaks) StringTokenizer Tokenizer = new StringTokenizer (Linevalu e); Traverse while (Tokenizer.hasmoretokens ()) {//Get each value String Wordvalue = TOKENIZER.N Exttoken (); Set the key value of the map output word.set (wordvalue); Context output Map processing results context.write (word, one); }}}/** * Reducer zone: WordCount program Reduce class * Reducer<keyin, Valuein, Keyout, Valueout>:map The output type is the reduce The input type * @author Johnnie * */public static class Intsumreducer extends Reducer<text, intwritable, Text, intwritable> {//output: Total number of private intwritable result = new intwritable (); @Override public void reduce (Text key, iterable<intwritable> values, context context) throws IOException, Int erruptedexception {int sum = 0; Accumulator, summing up the total number of occurrences per word//Traverse values for (intwritable val:values) {sum + = Val.get (); Accumulate}//Set output value result.set (sum); Context output reduce result context.write (key, result); }}//Driver zone: Client public static void main (string[] args) throws Exception {//Get configuration information Configurati On conf = new Configuration (); Create a job Job Job = job.getinstance (conf, "word count"); Set the job name to Word count//job = new Job (conf, "word count"); Outdated way//1. Set the class Job.setjarbyclass (Wordcount.class) of the Job run; 2. Set Mapper class and Reducer class Job.setmapperclass (Tokenizermapper.class); Job.setreducerclass (Intsumreducer.class); 3. Get input parameters, set input file directory and output file directory Fileinputformat.addinputpath (Job, New Path (Args[0])); Fileoutputformat.setoutputpath (Job, New Path (Args[1])); 4. Sets the output result type Job.setoutputkeyclass (text.class) of key and value; Job.setoutputvalueclass (Intwritable.class);//Job.setcombinerclass (Intsumreducer.class); 5. Submits the job, waits for the result to run, and displays the run information on the client, and finally ends the program, Boolean issuccess = Job.waitforcompletion (true); End Program System.exit (Issuccess 0:1); }}
④ Write Main.java: We configure a program to execute the portal, to facilitate the subsequent addition of other examples, the appearance of the official jar
⑤ We package the project as an executable jar package: Here I name the jar Wordcount.jar
⑥ use FileZilla to upload the jar package to the CenOS6.5
⑦ uses the Hadoop jar command to execute the program. Execute command:hadoop jar Wordcount.jar wordcount./data/f*.txt/out
注:这种传参方式就是 Linux下参数传递的方式。这里也介绍了我们平时在 Java 程序中 main() 中 args 的使用--就是来接受命令行参数的。
Specific steps, or just the same, prepare the input file, and specify the output directory. The path to the input file and output directory is on the HDFS file system:/data/f*.txt is similar to the F1.txt and F2.txt. The output is not much to say, also similar.
Java Notes---The WordCount program in Hadoop 2.7.1