MapReduce如何实现WordCount及其优化

这期内容当中小编将会给大家带来有关MapReduce如何实现WordCount及其优化,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:主机域名雅安服务器托管、营销软件、网站建设、太仓网站维护、网站推广。

WordCount: 单词计数, 统计文本文件中每一个单词出现的次数

定义Mapper类, 该类继承org.apache.hadoop.mapreduce.Mapper

并重写map()方法

public static class TokenizerMapper extends
			Mapper<LongWritable, Text, Text, IntWritable> {
	        // 定义一个静态成员变量, 并且是不可变的, 避免每一次调用map()方法时, 创建重复对象
		private final static IntWritable one = new IntWritable(1);
		// 定义一个成员变量, 可变, 每一次调用map()方法时, 只需要调用Text.set()方法赋新值
		private Text word = new Text();

		public void map(LongWritable key, Text value, Context context)
				throws IOException, InterruptedException {
			String[] words = value.toString().split(" ");
			for (String item : words) {
				word.set(item);
				context.write(word, one);
			}
		}
	}

定义Reducer类, 该类继承org.apache.hadoop.mapreduce.Reducer

并重写reduce()方法

public static class IntSumReducer extends
			Reducer<Text, IntWritable, Text, IntWritable> {
		// 定义一个成员变量, 可变, 每一次调用reduce()方法时, 只需要调用IntWritable.set()方法赋新值
		private IntWritable result = new IntWritable();

		public void reduce(Text key, Iterable<IntWritable> values,
				Context context) throws IOException, InterruptedException {
			int sum = 0;
			for (IntWritable val : values) {
				sum += val.get();
			}
			result.set(sum);
			context.write(key, result);
		}
	}

测试WordCount

public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		job.setJarByClass(WordCount.class); // 设置job的主类
		job.setMapperClass(TokenizerMapper.class); // 设置Mapper类
		// 利用combiner来减少通过shuffle传输的数据量
		job.setCombinerClass(IntSumReducer.class); // 设置Combiner类
		job.setReducerClass(IntSumReducer.class); // 设置Reducer类
		job.setMapOutputKeyClass(Text.class); // 设置map阶段输出Key的类型
		job.setMapOutputValueClass(IntWritable.class); // 设置map阶段输出Value的类型
		job.setOutputKeyClass(Text.class); // 设置reduce阶段输出Key的类型
		job.setOutputValueClass(IntWritable.class); // 设置reduce阶段输出Value的类型
		// 设置job输入路径(从main方法参数args中获取)
		FileInputFormat.addInputPath(job, new Path(args[0]));
		// 设置job输出路径(从main方法参数args中获取)
		FileOutputFormat.setOutputPath(job, new Path(args[1]));

		job.waitForCompletion(true); // 提交job
	}

输入: 

words:

hello tom
hello jerry
hello kitty
hello world
hello tom

输出:

hello	5
jerry	1
kitty	1
tom	2
world	1

减少对象的创建, 更少的GC, 肯定会带来更快的速度

利用combiner来减少通过shuffle传输的数据量, 这是MapReduce作业调优的关键点之一

上述就是小编为大家分享的MapReduce如何实现WordCount及其优化了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。

分享标题:MapReduce如何实现WordCount及其优化
文章网址:https://www.cdcxhl.com/article8/gedsip.html

成都网站建设公司_创新互联,为您提供Google建站公司定制开发网站设计网页设计公司云服务器

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

小程序开发