1. MR执行原理
1. MAP阶段

2. Reducer

3.shuffle阶段

2.实操
1. 导入 maven 配置
<!-- MR 操作 -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-common</artifactId>
<version>2.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hadoop/hadoop-mapreduce-client-core -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-core</artifactId>
<version>2.7.1</version>
</dependency>
2. 配置自定义的 Mapper
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class WorkMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] lineValues = value.toString().split(" ");
for (String line : lineValues) {
context.write(new Text(line), new IntWritable(1));
}
}
}
3. 配置Reducer
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class WorkReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
Integer count = 0;
for (IntWritable value : values) {
count += value.get();
}
context.write(key, new IntWritable(count));
}
}
4. 启动类
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.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WorkDriver {
public static void main(String[] args) throws Exception {
System.setProperty("HADOOP_USER_NAME","root");
System.setProperty("hadoop.home.dir", "E:\\dev\\hadoop");
Configuration configuration = new Configuration();
configuration.set("fs.defaultFS","hdfs://192.168.80.111:9000");
Job job = Job.getInstance(configuration);
job.setJarByClass(WorkDriver.class);
job.setMapperClass(WorkMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setReducerClass(WorkReduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.setInputPaths(job,new Path("/input/wordcount"));
FileOutputFormat.setOutputPath(job,new Path("/output/out1"));
boolean isSuccess = job.waitForCompletion(true);
System.out.println(isSuccess);
}
}