WCJob.java
程序执行的入口,主要设置一些配置文件和指定map类和reduce类
package com.wang.wc;
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 WCJob {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//默认为src目录下的配置文件
Configuration conf = new Configuration();
//其他方法设置conf
// conf.set("fs.defaultFS", "hdfs://namenode:9000");
// conf.set("yarn.resourcemanager.hostname", "namenode");
//该方法需要将项目打包成jar包,放入hadoop集群中执行
// conf.set("mapred.jar","C:\\Users\\Adminstrator\\Desktop\\WorldCount.jar");
Job job = Job.getInstance(conf);
//在hadoop集群上运行这个作业时,要把代码打包成jar文件,
//hadoop利用这个类来查找包含它的jar文件,进而找到相关的jar文件
job.setJarByClass(WCJob.class);
//指定map类型和reduce类型
job.setMapperClass(WCMapper.class);
job.setReducerClass(WCReducer.class);
//setMapOutputKeyClass和setMapOutputValueClass控制map和reduce函数的输出类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
//使用FileInputFormat类制定输入数据和输出数据的文件地址
FileInputFormat.addInputPath(job, new Path("/wc/input/wc"));
Path outpath = new Path("/wc/output");
FileSystem fs = FileSystem.get(conf);
//-----
if(fs.exists(outpath)){
fs.delete(outpath, true);
}
FileOutputFormat.setOutputPath(job, outpath);
boolean flag = job.waitForCompletion(true);
if(flag){
System.out.println("success!");
}
}
}
该类指定map方法
WCMapper.java
map类是一个泛型类型,有四个形参类型,分别指定map函数的输入key类型,输入value类型,输出key类型,输出value类型。
package com.wang.wc;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
//LongWritable相当于java的Long类型,Text相当于java中的String类型,这些类都在org.apache.hadoop.io包中
public class WCMapper extends Mapper<LongWritable, Text, Text, IntWritable>{
@Override
protected void map(LongWritable key,Text value,Context context) throws IOException, InterruptedException{
//将Text类型转换为String类型
String str = value.toString();
String[] strs = StringUtils.split(str,' ');
Context实例用于输出内容的写入
for(String s:strs){
context.write(new Text(s), new IntWritable(1));
}
}
}
该类指定reduce方法
package com.wang.wc;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class WCReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
@Override
protected void reduce(Text text, Iterable<IntWritable> iterable,
Context context)
throws IOException, InterruptedException {
int sum = 0;
for(IntWritable i :iterable){
sum += i.get();
}
context.write(text, new IntWritable(sum));
}
}