Hadoop深入学习:Partitioner组件的设计与实现

本节我们来学习MapReduce编程框架中的Partitioner接口和其他相关的信息。
Partitioner的作用就是对Mapper产生的中间数据进行分片,以便将同一分片的数据交给同一个Reducer处理,该过程是MapReduce的shuffle过程,特别是Map端的shuffle的一部分。
[b]Partitioner它直接影响Reduce阶段的负责均衡。[/b]在老版中,Partitioner是一个接口,继承了JobConfigurable接口,代码如下:

/**
* Partitions the key space.
*
* <p><code>Partitioner</code> controls the partitioning of the keys of the
* intermediate map-outputs. The key (or a subset of the key) is used to derive
* the partition, typically by a hash function. The total number of partitions
* is the same as the number of reduce tasks for the job. Hence this controls
* which of the <code>m</code> reduce tasks the intermediate key (and hence the
* record) is sent for reduction.</p>
*
* @see Reducer
*/
public interface Partitioner<K2, V2> extends JobConfigurable {

/**
* Get the paritition number for a given key (hence record) given the total
* number of partitions i.e. number of reduce-tasks for the job.
*
* <p>Typically a hash function on a all or a subset of the key.</p>
*
* @param key 基于该key对数据分组儿.
* @param value the entry value.
* @param numPartitions 每个Mapper的分片数.
* @return the partition number for the <code>key</code>.
*/
int getPartition(K2 key, V2 value, int numPartitions);
}

MapReduce提供了两个Partitioner实现类:HasdPartitioner和TotalOrderPartitioner。
默认情况下,MapReduce分布式计算模型使用的是HasdPartitioner,它实现了一种基于Hash值的分片算法:

/** Partition keys by their {@link Object#hashCode()}.
*/
public class HashPartitioner<K2, V2> implements Partitioner<K2, V2> {

public void configure(JobConf job) {}

/** Use {@link Object#hashCode()} to partition. */
public int getPartition(K2 key, V2 value,int numReduceTasks) {
return (key.hashCode() & Integer.MAX_VALUE) % numReduceTasks;
}

}


TotalOrderPartitioner主要用于Hadoop中的对数据进行全排序,它提供了一种基于区间的分片算法,能按照大小将数据分成若干个区间即分片,并保证后一个区间的所有数据都大于前一个区间的数据,这大大提高了全局排序的性能和扩展性。
使用TotalOrderPartitioner对数据进行全排序,要涉及到数据采样,需要和Hadoop采样器(如内置的IntercalSampler、RandomSampler和SplitSampler等,当然也可以实现直接的采样器)配合,具体步骤如下:
[b]第一步,数据采样。[/b]在Client端使用采样器(Sampler)获得分片的分割点;
[b]第二步,Map阶段。[/b]=在该阶段中涉及MapReduce编程模型的两个组件Mapper和Partitioner,Mapper可以采用IdentityMapper,直接输出数据,但Partitioner必须选用TotalOrderPartitioner,他将步骤1中获取的分割点保存到一颗trie树中,以便快速定位一个数据所在的区间。这样Mapper中产生的中间数据的N个区间就都是有序的;
[b]最后一步,[/b]Reduce阶段。在对每一个Reducer分配到的数据进行局部排序,最终得到经过全排序的数据。
[b]使用TotalOrderPartitioner的全排序的效率根key的分布规律和采样器的算法有直接关系。key值分布月均匀且采样越具有代表性,则Reduce Task负载月均衡,从而全排序的效率也就越高。[/b]

有兴趣的朋友可以看一看TotalOrderPartitioner的使用示例TeraSort,这个示例可以在examples\org\apache\hadoop\examples\terasort包中招的到。
在MapReduce编程框架中的其他两个组件Reduce和OutputFormat学习完后,鄙人会专门学习一下Hadoop的采样器Sampler和TotalOrderPartitioner,这里不再赘述。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值