Reducer组件的编写方法跟Mapper组件类似,它需要继承虚基类public HadoopPipes::Reducer。
与Mapper组件唯一不同的地方时,map函数的参数类型为HadoopPipes::ReduceContext,它包含一个nextValue()方法,这允许用于遍历当前key对应的value列表,依次进行处理。
接下来介绍RecordReader, Partitioner和RecordWriter的编写方法:
(3) RecordReader编写方法
用户自定义的RecordReader类需要继承虚基类HadoopPipes::RecordReader,它的声明如下:
- class RecordReader: public Closable {
- public:
- virtual bool next(std::string& key, std::string& value) = 0;
- virtual float getProgress() = 0;
- };
用户自定义的RecordReader的构造函数可携带类型为HadoopPipes::MapContext的参数,通过该参数的getInputSplit()的方法,用户可以获取经过序列化的InpuSplit对象,Java端采用不同的InputFormat可导致InputSplit对象格式不同,但对于大多数InpuSplit对象,它们可以提供至少三个信息:当前要处理的InputSplit所在的文件名,所在文件中的偏移量,它的长度。用户获取这三个信息后,可使用libhdfs库读取文件,以实现next方法。
下面介绍一下反序列化InputSplit对象的方法:
【1】 如果Java端采用的InputFormat为WordCountInpuFormat,可以这样:
- lass XXXReader: public HadoopPipes::RecordReader {
- public:
- XXXReader (HadoopPipes::MapContext& context) {
- std::string filename;
- HadoopUtils::StringInStream stream(context.getInputSplit());
- HadoopUtils::deserializeString(filename, stream);
- ……
- };
- class XXXReader: public HadoopPipes::RecordReader {
- public:
- XXXReader (HadoopPipes::MapContext& context) {
- std::string filename;
- HadoopUtils::StringInStream stream(context.getInputSplit());
- readString(filename, stream);
- int start = (int)readLong(stream);
- int len = (int)readLong(stream);
- ……
- private:
- void readString(std::string& t, HadoopUtils::StringInStream& stream)
- {
- int len = readShort(stream);
- if (len > 0) {
- // resize the string to the right length
- t.resize(len);
- // read into the string in 64k chunks
- const int bufSize = 65536;
- int offset = 0;
- char buf[bufSize];
- while (len > 0) {
- int chunkLength = len > bufSize ? bufSize : len;
- stream.read(buf, chunkLength);
- t.replace(offset, chunkLength, buf, chunkLength);
- offset += chunkLength;
- len -= chunkLength;
- }
- } else {
- t.clear();
- }
- }
- long readLong(HadoopUtils::StringInStream& stream) {
- long n;
- char b;
- stream.read(&b, 1);
- n = (long)(b & 0xff) << 56 ;
- stream.read(&b, 1);
- n |= (long)(b & 0xff) << 48 ;
- stream.read(&b, 1);
- n |= (long)(b & 0xff) << 40 ;
- stream.read(&b, 1);
- n |= (long)(b & 0xff) << 32 ;
- stream.read(&b, 1);
- n |= (long)(b & 0xff) << 24 ;
- stream.read(&b, 1);
- n |= (long)(b & 0xff) << 16 ;
- stream.read(&b, 1);
- n |= (long)(b & 0xff) << 8 ;
- stream.read(&b, 1);
- n |= (long)(b & 0xff) ;
- return n;
- }
- };
用户自定义的Partitioner类需要继承虚基类HadoopPipes:: Partitioner,它的声明如下:
- class Partitioner {
- public:
- virtual int partition(const std::string& key, int numOfReduces) = 0;
- virtual ~Partitioner() {}
- };
对于partition方法,框架会自动为它传入两个参数,分别为key值和reduce task的个数numOfReduces,用户只需返回一个0~ numOfReduces-1的值即可。
