Mapreduce初析java
Mapreduce是一個計算框架,既然是作計算的框架,那麼表現形式就是有個輸入(input),mapreduce操做這個輸入(input),經過自己定義好的計算模型,獲得一個輸出(output),這個輸出就是咱們所須要的結果。程序員
咱們要學習的就是這個計算模型的運行規則。在運行一個mapreduce計算任務時候,任務過程被分爲兩個階段:map階段和reduce階段,每一個階段都是用鍵值對(key/value)做爲輸入(input)和輸出(output)。而程序員要作的就是定義好這兩個階段的函數:map函數和reduce函數。apache
Mapreduce的基礎實例app
jar包依賴框架
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.7.6</version>
</dependency>函數
代碼實現oop
map類學習
public class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); 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); } } }
reduce類code
public class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> { private IntWritable result = new IntWritable(); 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); } }
main方法orm
public class WordCount { public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(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(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
打成jar包放到hadoop環境下
./hadoop-2.7.6/bin/hadoop jar hadoop-mapreduce-1.0.0.jar com.dongpeng.hadoop.mapreduce.wordcount.WordCount /user/test.txt /user/in.txt