map/reduce实例(一)

本文介绍了MapReduce的基础应用——WordCount,包括Mapper、Reducer和Driver的职责。接着深入讲解了如何使用Bean对象封装来处理更复杂的业务逻辑,例如统计手机号的上行、下行和总流量,并详细展示了Bean的定义、Mapper和Reducer的实现。最后,通过调整分区策略,实现了按手机号前三位进行分区的优化。
摘要由CSDN通过智能技术生成

map/reduce基础——wordcount

wordcount是map/reduce中最基础的一个案例,是一个入门练习案例。
map/reduce一般分为三个组件mapper、reducer、dirver。mapper和reducer负责业务逻辑,driver负责提交业务。

mapper如下

public class Mapwordc extends Mapper<LongWritable, Text, Text, IntWritable> {
	//该案例中ivalue的样式:hello world ni hao zm love
	@Override
	public void map(LongWritable ikey, Text ivalue, Context context) throws IOException, InterruptedException {
		//map task 从文件按行读取<key,value>,第一个key默认是行偏移量,value是一行的数据
		//把第一行数据转成字符串存放在line变量中
		String line = ivalue.toString();
		//按照空格将字符串line进行切分,存放在字符数组words[]中
		String words [] = line.split(" ");
		//遍历words数组,将其中的word作为key,进行输出,输出的<k,v>格式为<key,1>
		for (String word:words) {
			context.write(new Text(word), new IntWritable(1));
		}
	}

reducer如下

//reducer获得的数据格式如下:<hello,1>、< world,1>、< ni,1>、< hao,1>、< zm,1>、< love,1>
	//reducer获得的key是Text,value是整形1
	@Override
	public void reduce(Text _key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
		// process values
		//设置一个变量进行计数
		int count = 0;
		
		//遍历values每个values都是1,每有一个value都在count上加一计数
		for(IntWritable value:values) {
			count+=value.get();
		}
		
		//同样是遍历values和上面效果一样。
		/*Iterator<IntWritable> iterator = values.iterator();
		while(iterator.hasNext()) {
			IntWritable value = iterator.next();
			count += value.get();
		}*/
		
		//输出<key,value>,key就是map传进来的key,value是对key的计数count
		context.write(_key, new IntWritable(count));
		
	}

driver程序

public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf,"driwordc"
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值