1.准备环境
- Windows下的Hadoop的mapred-site.xml 和 yarn-site.xml配置文件更新为和虚拟机中的一样。
- 将mapred-site.xml和yarn-site.xml配置文件拷贝到工程下。
- 添加依赖包。
2.运行模式
- 本地运行(在本地的eclipse中启动多个线程来模拟map task,和reduce task执行)。主要用于测试环境。
需要修改mapred-site.xml配置文件中的 mapreduce.framework.name,修改为local。 - 提交到集群中运行。主要用于生产环境。
需要先将工程打成一个jar包,拷贝到虚拟机中。使用hadoop jar命令执行。 - 在本机上的eclipse中直接提交任务到集群中运行。
需要先将工程达成一个jar包,放在本地一个地方。比如d盘下。然后在程序中设置job.setJar(“jar包的路径”)。最后还要修改mapred-site.xml配置文件为
<property>
<name>mapreduce.framework.name</name>
<value>yarn</value>
</property>
<property>
<name>mapreduce.app-submission.cross-platform</name>
<value>true</value>
</property>
3.一个简单的wordcount实例,用于统计一篇文章中某个单词出现的次数
- 主函数
public class WC {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
//设置配置对象
Configuration conf = new Configuration(true);
//设置一个job对象
Job job = Job.getInstance(conf);
//设置当前main函数所在类
job.setJarByClass(WC.class);
//需要使用到第三种运行模式时要设置本地jar包的位置
job.setJar("d:/wc.jar");
//设置输入路径
FileInputFormat.setInputPaths(job, "/input/wc");
//设置输出路径
Path outputPath = new Path("/output/");
FileSystem fs = outputPath.getFileSystem(conf);
//判断这个输出路径是否存在,存在就把它删除
if(fs.exists(outputPath)){
fs.delete(outputPath,true);
}
FileOutputFormat.setOutputPath(job, outputPath);
//设置Map class
job.setMapperClass(WCMapper.class);
//设置map输出key、value的类型 key是单词,value是1
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
//设置reduce class
job.setReducerClass(WCReduce.class);
//设置reduce task的个数
job.setNumReduceTasks(2);
//打印信息
job.waitForCompletion(true);
}
}
- Map class
public class WCMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
Text myKey = new Text();
IntWritable myValue = new IntWritable(1);
@Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
//根据空格将单词切割出来
String[] words = StringUtils.split(value.toString(), ' ');
for (String word : words) {
myKey.set(word);
context.write(myKey,myValue);
}
}
}
- Reduce class
public class WCReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
protected void reduce(Text key, Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable value : values) {
sum += value.get();
}
context.write(key, new IntWritable(sum));
}
}