1

最近、Hadoopを学び始めました。ここで、ローカルディスクのファイルを開き、reduce関数でそのファイルにデータを書き込みたいのですが、そのファイルを閉じるための適切な方法が見つかりませんでした。

私の知る限り、それを閉じて再び開くのは良い考えではないので、私はそれをしたくありません。

public class MyClass extends Configured implements Tool{
    main(){
         //all configurations here
         job.setMapperClass(MyMapper.class);
         job.setReducerClass(MyReducer.class);
    }
    static class MyMapper extends Mapper <LongWritable,Text,Text,Text>{
      //does something
    }
    static class MyReducer extends Reducer <LongWritable,Text,Text,Text>{
         //create file, filewriter etc here
         public MyReducer() {
              //open a file here
         }
         public reduce(){
              //write to file here
              bw.write("entered the reduce task for " + key); 
              while(there is more item)
                  bw.write( value + " will be written to my file \n");
         }
    }
}

ワークフローは次のようになります(間違っている場合は修正してください)。

for(each reduce task)
    write to file "entered the reduce task for " + *key*
        for each *value* for that *key*
            write *value*

ローカルディスクに書き込まれたmyfileにキーと値のペアを書き込み、ファイルを閉じたいのですが、その問題の適切な解決策が見つかりません。それとも、ファイルを閉じないと、問題になりますか?つまり、Hadoopがそれを処理しているのでしょうか?

ありがとう、

4

1 に答える 1

1

拡張するマッパー クラスとリデューサー クラスの両方に、データを処理する前後にコードを実行するメソッドがあります。

  • map/reduce の実行前にコードを実行するには、setup(Context context)メソッドを拡張します
  • map/reduce タスクの完了後にコードを実行するには、cleanup(Context context)メソッドを拡張します

したがって、あなたの場合、 close メソッドを拡張してファイルを閉じることができます。(開いているストリームへのレデューサーでインスタンス変数を維持する必要があります)。

reduce メソッドで失敗/例外が発生した場合、close メソッドは呼び出されないことに注意してください (reduce メソッド自体をオーバーライドして例外をトラップし、close メソッドを実行してから例外を再スローしない限り)。

于 2013-03-19T10:50:18.577 に答える