1.WordMapper.java
package WordCount;
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 WordMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
final IntWritable ONE = new IntWritable(1);
String s = value.toString();
String[] words = s.split(" ");
for (String word : words) {
context.write(new Text(word), ONE);
}
}
}
2.WordReducer.java
package WordCount;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class WordReducer extends Reducer<Text, IntWritable, Text, LongWritable> {
@Override
protected void reduce(Text key, Iterable<IntWritable> values,
Reducer<Text, IntWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
long count = 0;
for (IntWritable value : values) {
count += value.get();
}
context.write(key, new LongWritable(count));
}
}
3.Test.java
package WordCount;
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.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class Test {
public static void main(String[] args) throws Exception{
Configuration conf = new Configuration();
conf.set("fs.defaultFS","hdfs://master:9000/");
conf.set("mapreduce.job.jar", "out/artifacts/HelloMapReduce.jar");
conf.set("mapreduce.framework.name","yarn");
conf.set("mapreduce.jobhistory.address","192.168.56.100:10020");
conf.set("yarn.resourcemanager.hostname","master");
conf.set("mapreduce.app-submission.cross-platform", "true");
Job job = Job.getInstance(conf);
// job.setJarByClass(Test.class);
job.setMapperClass(WordMapper.class);
job.setReducerClass(WordReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
FileInputFormat.setInputPaths(job, "/hello.txt");
FileOutputFormat.setOutputPath(job, new Path("/output/"));
job.waitForCompletion(true);
}
}
4.生成jar包
参考 https://www.cnblogs.com/airnew/p/9540982.html
5.运行结果
mapreduce1.png
map.png
reduce.png
mapreduce2.png
mapreduce生成output.png
mapreduce-result.png
网友评论