在eclipse中实现MapReduce

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));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值