MapReduce編程模型
【1】先對輸入的信息進行切片處理。
【2】每個map函數對所劃分的數據並行處理,產生不同的中間結果輸出。
【3】對map的中間結果數據進行收集整理(aggregate & shuffle)處理,交給reduce。
【4】reduce進行計算最終結果。
【5】彙總所有reduce的輸出結果。
【名詞解釋】
ResourceManager:是YARN資源控制框架的中心模塊,負責集羣中所有的資源的統一管理和分配。它接收來自NM(NodeManager)的彙報,建立AM,並將資源派送給AM(ApplicationMaster)。
NodeManager:簡稱NM,NodeManager是ResourceManager在每臺機器的上代理,負責容器的管理,並監控他們的資源使用情況(cpu,內存,磁盤及網絡等),以及向 ResourceManager提供這些資源使用報告。
ApplicationMaster:以下簡稱AM。YARN中每個應用都會啓動一個AM,負責向RM申請資源,請求NM啓動container,並告訴container做什麼事情。
Container:資源容器。YARN中所有的應用都是在container之上運行的。AM也是在container上運行的,不過AM的container是RM申請的。
【用Java來實現WordCount單詞計數的功能】
package com.yc.hadoop42_003_mapreduce;
import java.io.IOException;
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;
public class MyWordCount {
//Mapper靜態內部類
public static class MyWordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
public static final IntWritable ONE = new IntWritable(1);
@Override
protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
//按空格分割,map默認的value是每一行
String[] words = value.toString().split("\\s");
for (String word : words) {
context.write(new Text(word), ONE);
}
}
}
//Reducer靜態內部類
public static class MyWordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
protected void reduce(Text key, Iterable<IntWritable> value,
Reducer<Text, IntWritable, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
int count = 0;
for (IntWritable v : value) {
count += v.get(); // 統計單詞個數
}
context.write(new Text(key), new IntWritable(count));
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(); // 配置文件對象
Job job = Job.getInstance(conf, "mywordCount"); // mapreduce作業對象
// 設置map操作
job.setMapperClass(MyWordCountMapper.class); //設置map處理類
job.setMapOutputKeyClass(Text.class); //設置拆分後,輸出數據key的類型
job.setMapOutputValueClass(IntWritable.class); //設置拆分後,輸入數據value的類型
// 設置reduce操作
job.setReducerClass(MyWordCountReducer.class); //設置reduce處理類
//這裏reduce輸入輸出格式一致,不需要再次設置
// 設置輸入輸出
FileInputFormat.setInputPaths(job, new Path("hdfs://master:9000/in/data03.txt"));// 設置處理數據文件的位置
FileOutputFormat.setOutputPath(job, new Path("hdfs://master:9000/result"));// 設置處理後文件的存放位置
// 開始執行mapreduce作業
job.waitForCompletion(true);
}
}
【結果】