(二)MR之reduce多目錄輸出

第一步: MultipleOutputs.addNamedOutput()

main或run方法中註冊,其中namedOutput爲別名,不能是中文,不能包含下劃線_ MultipleOutputs.addNamedOutput(Job job, String namedOutput, Class<? extends OutputFormat> outputFormatClass, Class<?> keyClass, Class<?> valueClass);ide

String dirName[] = acts.split(Constant.MARK_AITE);
        for (String a : dirName) {
            MultipleOutputs.addNamedOutput(job, a, TextOutputFormat.class,
                    NullWritable.class, Text.class);
        }
        logger.info("---excuter---");

***插播 詳細介紹一下 MultipleOutputs.addNamedOutput(job, a, TextOutputFormat.class,

NullWritable.class, Text.class)

第二步:

而後就能夠用mos.write(Key key,Value value,String baseOutputPath)代替context.write(key, value);函數

注意:multipleOutputs.write(key, value, baseOutputPath)方法的第三個函數代表了該輸出所在的目錄(相對於用戶指定的輸出目錄)。 若是baseOutputPath不包含文件分隔符「/」,那麼輸出的文件格式爲baseOutputPath-r-nnnnn(name-r-nnnnn); 若是包含文件分隔符「/」,例如baseOutputPath=「029070-99999/1901/part」,那麼輸出文件則爲029070-99999/1901/part-r-nnnnncode

public static class AutoActLogParseReducer extends Reducer<Text, Text, NullWritable, Text> {

        private MultipleOutputs<NullWritable, Text> mos; // 輸出類型和Reduce一致

        @Override
        protected void setup(Reducer<Text, Text, NullWritable, Text>.Context context)
                throws IOException, InterruptedException {
            mos = new MultipleOutputs<NullWritable, Text>(context);
        }

        @Override
        protected void cleanup(
                Reducer<Text, Text, NullWritable, Text>.Context context)
                throws IOException, InterruptedException {

            mos.close();
        }

        @Override
        public void reduce(Text key, Iterable<Text> values, Context context)
                throws IOException, InterruptedException {
            Text valText = new Text();
            Text keyValue = new Text();
            Iterator<Text> it = values.iterator();
            String keyStr = key.toString();

            while (it.hasNext()) {
                String[] uk = it.next().toString().split(Constant.MARK_LINE);
                for (String tmpUk : uk) {
                    valText.set(tmpUk);

                    mos.write(keyStr, NullWritable.get(), valText, keyStr + "/");
                }
            }

        }

    }
相關文章
相關標籤/搜索