- 可靠的与不可靠的bolt
也可以使用IBasicBolt接口实现自动确认:
即,如果bolt不是extends BaseRichBolt,而是extends BaseBasicBolt,上面的代码中不可靠的bolt自动变为可靠的了。
2.关于declareOutputFields方法需要重点说一下。
在此方法中定义fields,它和nextTuple中的emit中的参数需要对应。
如:定义一个字串字段,则emit时需发送一个字串:
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word"));
}
public void nextTuple() {
Utils.sleep(100);
final Random rand = new Random();
String word = _words[rand.nextInt(_words.length)];
_collector.emit(new Values(word));
}
如果定义为多个字段,则emit时也需要发送相应字段:
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word", "count", "key"));
}
public void execute(Tuple tuple) {
String streamId = tuple.getSourceStreamId();
if (streamId.equals("stop")){
Iterator iter = counts.keySet().iterator();
while (iter.hasNext()){
String keyword = (String) iter.next();
Integer nCount = (Integer) counts.get(keyword);
collector.emit(tuple, new Values(keyword, nCount, tuple.getStringByField("key")));
}
this._collector.ack(tuple);
counts.clear();
}
}
Bolt的下一个topo节点的execute方法可通过getString方法获取值,如,接受上面的三个参数:
public void execute(Tuple tuple) {
Integer count = tuple.getIntegerByField("count");
String key = tuple.getStringByField("key");
String word = tuple.getStringByField("word");
}
3. 关于按字段分组参数
在topology中使用字段分组时需要指定字段名,这个值即是上一个源(spout/bolt)中定义的fields。如:
builder.setSpout("wordSpout", new WordSpout(), 4);
builder.setBolt("CountBolt", new CountBolt(), 4)
.fieldsGrouping("wordSpout", "working", new Fields("word"))
.allGrouping("wordSpout", "stop");
builder.setBolt("SummaryBolt", new SummaryBolt(), 4).fieldsGrouping("CountBolt", new Fields("key"));
SummaryBolt使用的是按字段分组,它将使用CountBolt的key字段进行分组。