package com.zjs.mr;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class WordCountMap extends Mapper<LongWritable, Text, Text, IntWritable>{
Text outKey = new Text(); //设置变量存储每次分隔出的单词
IntWritable num = new IntWritable();
@Override
protected void map(LongWritable key, Text value,
Context context)
throws IOException, InterruptedException {
//取得一行记录
String line = value.toString();
//从一行中获取每个单词
StringTokenizer st = new StringTokenizer(line);
//循环遍历取出每个单词,并设置出现一次
while(st.hasMoreTokens()){
String word = st.nextToken();
outKey.set(word);
num.set(1);//只要单词出现一次就设置1,然后交给reducer叠加
context.write(outKey, num);//以单词位key值
}
}
}
package com.zjs.mr;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
@Override
protected void reduce(Text key, Iterable<IntWritable> iter,
Context context)
throws IOException, InterruptedException {
int sum = 0 ;//用来叠加每个单词出现的次数
for(IntWritable i : iter){
sum = sum + i.get();
}
context.write(key, new IntWritable(sum));
}
}
package com.zjs.mr;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
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 JobRun {
public boolean run() throws Exception{
Configuration config = new Configuration();
config.set("fs.defaultFS", "hdfs://node6:8020");
config.set("yarn.resourcemanager.hostname", "node7");
//取得文件系统
FileSystem fs = FileSystem.get(config);
Job job = Job.getInstance(config);
//设置任务调度类
job.setJarByClass(JobRun.class);
//设置mapper
job.setMapperClass(WordCountMap.class);
job.setReducerClass(WordCountReducer.class);
//执行Combiner程序
job.setCombinerClass(WordCountReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
//指定MR的输入数据(文件)
FileInputFormat.addInputPath(job, new Path("/usr/input/wc/test"));
//指定MR输出数据目录,该目录不能存在,MR在启动之处要检查该目录是否存在,如果存在报错。
Path outpath =new Path("/usr/output/wc");
if(fs.exists(outpath)){
fs.delete(outpath, true);
}
FileOutputFormat.setOutputPath(job, outpath);
//执行该任务(MR),并等待MR完成
return job.waitForCompletion(true);
}
public static void main(String[] args) {
JobRun jr =new JobRun();
try {
System.out.println(jr.run() ?"执行成功":"执行失败");
} catch (Exception e) {
e.printStackTrace();
}
}
}