【发布时间】:2015-02-17 10:26:51
【问题描述】:
我有一个简单的螺栓,它从 kafka spout 读取数据,然后应该将数据写入 HDFS 目录。问题是在集群停止之前,bolt 不会写入。我如何确保当螺栓从 kafka spout 读取一个元组时,它会立即将其写入 HDFS,或者至少写入每个“n”个条目。 (我使用的是 CDH 4.4、Hadoop 2.0)
螺栓的java:
public class PrinterBolt10 extends BaseRichBolt{
private OutputCollector collector;
private String values;
Configuration configuration = null;
FileSystem hdfs = null;
FSDataOutputStream outputStream=null;
BufferedWriter br = null;
List<String> valList;
String machineValue;
int upTime;
int downTime;
int idleTime;
public void prepare(Map config, TopologyContext context,OutputCollector collector) {
upTime=0;
downTime=0;
idleTime=0;
this.collector = collector;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
try{
configuration = new Configuration();
configuration.set("fs.defaultFS", "hdfs://localhost.localdomain:8020");
hdfs =FileSystem.get(configuration);
outputStream = hdfs.create(new Path("/tmp/storm/StormHdfs/machine10_"+timeStamp+".txt"));
br = new BufferedWriter( new OutputStreamWriter( outputStream , "UTF-8" ) );
br.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void execute(Tuple tuple) {
values = tuple.toString();
int start = values.indexOf('[');
int end = values.indexOf(']');
machineValue=values.substring(start+1,end);
String machine=machineValue.substring(0,machineValue.indexOf(','));
String code = machineValue.substring(machineValue.indexOf(',')+1);
int codeInt = Integer.parseInt(code);
if(codeInt==0) idleTime+=30;
elseif(codeInt==1) upTime+=30;
else downTime+=30;
String finalMessage = machine + " "+ "upTime(s) :" + upTime+" "+ "idleTime(s): "+idleTime+" "+"downTime: "+downTime;
try {
br.write(finalMessage); // *This is the writing part into HDFS*
br.write('\n');
br.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
// this bolt does not emit anything
}
public void cleanup() {}
}
【问题讨论】:
-
虽然这不是您问题的直接答案,但您也可以考虑将 Storm 输出写回 Kafka(您已经从 Kafka 读取,因此基础设施存在),然后使用诸如作为 LinkedIn Camus 负责(批量)将数据从 Kafka 加载到 HDFS。这种方法也可能更安全,因为从 Storm 直接写入 HDFS 可能会导致重复数据,请参阅blog.thedatateam.in/2015/02/guaranteeing-exactly-once-load.html。
标签: java hadoop hdfs apache-storm