最近在學習hadoop,安裝的版本是hadoop2.7.3。
思考着如何把編寫好的mapreduce內容部署到hadoop中並運行這個程序,下面記錄了這部分實踐內容。上面代碼打包 hadoop-test.jar,打包方式任選。
package com.ksy.hadoop; 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.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 org.apache.hadoop.util.GenericOptionsParser; /** * 該例子為網上經典例子統計單詞出現次數 * */ public class WordCount { public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); /** * key 偏移量包括了回車所占的字符數(Windows和Linux環境會不同) * value 一行數據 * context存儲新Map的對象 */ public void map(Object key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { word.set(itr.nextToken()); context.write(word, one); } } } public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); /** * key 為Map中的key,hadoop會把相同key的內容合並為一個list,該list就為values。 * context為存放結果的對象 */ public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length != 2) { System.err.println("Usage: wordcount <in> <out>"); System.exit(2); } Job job = new Job(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(otherArgs[0])); FileOutputFormat.setOutputPath(job, new Path(otherArgs[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
- 上傳包到部署有hadoop的機器上,本例子上傳到/home/hadoop目錄。
- 用工具putty/SecureCRT登錄到系統,進入hadoop/bin目錄下。
- 運行命令./hadoop jar ~/hadoop-test.jar com.ksy.hadoop.WordCount /user/hadoopfile output,這樣就把該例子運行了,通過./hdfs dfs -ls /user/hadoop/output/可以查看到運行后生成了兩個文件
hadoop@ubuntu-114:/usr/local/hadoop/bin$ ./hdfs dfs -ls /user/hadoop/output/ Found 2 items -rw-r--r-- 1 hadoop supergroup 0 2017-07-25 19:00 /user/hadoop/output/_SUCCESS -rw-r--r-- 1 hadoop supergroup 57649 2017-07-25 19:00 /user/hadoop/output/part-r-00000
其中/user/hadoopfile是需要分析的hdfs文件,該文件可以通過shell命令上傳到hdfs中,output是輸出目錄。