MapReduce中自定义Combiner

 以下作为自己的学习记录。

1 MapReduce中数据的整个处理流程。

 

  Map输出数据->key排序并且计算partintion->Map本地所有数据数据Combiner->

shuffle中的自定义排序->自定义分组->reduce中数据汇总

例子:

一、 自定义Combiner使用

1 自定义Combiner

  

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class MyCombiner extends Reducer<Text, LongWritable, Text, LongWritable> {
	
	protected void reduce( Text key, Iterable<LongWritable> values, Context context) throws java.io.IOException, InterruptedException {
		
		// 显示次数表示规约函数被调用了多少次,表示k2有多少个分组
		System.out.println("Combiner输入分组<" + key.toString() + ",N(N>=1)>");
		long count = 0L;
		for (LongWritable value : values) {
			count += value.get();
			// 显示次数表示输入的k2,v2的键值对数量
			System.out.println("Combiner输入键值对<" + key.toString() + "," + value.get() + ">"+this);
		}
		context.write(key, new LongWritable(count));
		// 显示次数表示输出的k2,v2的键值对数量
		System.out.println("Combiner输出键值对<" + key.toString() + "," + count + ">");
	};
}

 2  主类的使用

 

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class MyCombiner extends Reducer<Text, LongWritable, Text, LongWritable> {
	
	protected void reduce( Text key, Iterable<LongWritable> values, Context context) throws java.io.IOException, InterruptedException {
		
		// 显示次数表示规约函数被调用了多少次,表示k2有多少个分组
		System.out.println("Combiner输入分组<" + key.toString() + ",N(N>=1)>");
		long count = 0L;
		for (LongWritable value : values) {
			count += value.get();
			// 显示次数表示输入的k2,v2的键值对数量
			System.out.println("Combiner输入键值对<" + key.toString() + "," + value.get() + ">"+this);
		}
		context.write(key, new LongWritable(count));
		// 显示次数表示输出的k2,v2的键值对数量
		System.out.println("Combiner输出键值对<" + key.toString() + "," + count + ">");
	};
}

 

3 自定义Partition

  

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Partitioner;

 

public class MyPartintioner extends Partitioner<Text, LongWritable>{
 
	/**
	 * key map输出的key
	 * value map 输出的value 
	 */
	@Override
	public int getPartition(Text key, LongWritable value, int numPartitions) {
		
//		   System.out.println("--------enter DefinedPartition flag--------"); 
	        /** 
	        * 注意:这里采用默认的hash分区实现方法 
	        * 根据组合键的第一个值作为分区 
	        * 这里需要说明一下,如果不自定义分区的话,mapreduce框架会根据默认的hash分区方法, 
	        * 将整个组合将相等的分到一个分区中,这样的话显然不是我们要的效果 
	        */
//		   System.out.println(key+ "--------out DefinedPartition flag--------"+ value );
			System.out.println("Partitioner  key:"+key+"  value:"+value+"  "+ ( ( key.hashCode()&Integer.MAX_VALUE)%numPartitions ) +"   "+this);
	       return ( key.hashCode()&Integer.MAX_VALUE)%numPartitions; 
	}
	
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值