partitioner是在mapreduce的map过程之后,将mapper输出文件分成几个文件,再交由reducer处理。
之前老以为是在reducer阶段进行的partitioner,所以导致自己写了分区类,有了不同的文件输出,但是输出文件中的其中一个文件什么都没有。
code:
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Partitioner;
/**
* @Description: 实现分别输出到不同的文件
* @Date:2018-10-19
*/
public class MyPartitoner extends Partitioner<Text, IntWritable> {
public int getPartition (Text key, IntWritable values, int numPartioner) throws IndexOutOfBoundsException{
//int i = Integer.parseInt(values.toString());
//int a = i % numPartioner;
String str = key.toString();
char ch = str.charAt(0);
switch (ch){
case 'a' :
return 0;
case 'b' :
return 1;
default:
return 2;
}
}
}
这是一个wordcount程序,改写之后,会出现三个分区文件,一个文件里面只存放统计了a的次数记录。一个文件里面只存放统计b的次数记录,第三个文件就存放统计其他字符的次数记录。
主函数设置:
Information:你要生成几个输出文件,就需要设置多少个NumReduceTasks
再贴一个partitoner的源码:
重写自己的partitioner的时候就需要重写getPartition方法,这是一个抽象方法,继承Partitioner类的时候,必须给他实现。