更新时间:2024-08-05 GMT+08:00

创建Strom Spout

功能介绍

Spout是Storm的消息源,它是Topology的消息生产者,一般来说消息源会从一个外部源读取数据并向Topology中发送消息(Tuple)。

一个消息源可以发送多条消息流Stream,可以使用OutputFieldsDeclarer.declarerStream来定义多个Stream,然后使用SpoutOutputCollector来发射指定的Stream。

代码样例

下面代码片段在com.huawei.storm.example.common包的“RandomSentenceSpout”类的“nextTuple”方法中,作用在于将收到的字符串拆分成单词。

/**  
   * {@inheritDoc}  
   */  
  @Override  
  public void nextTuple()  
  {  
      Utils.sleep(100);  
      String[] sentences =  
          new String[] {"the cow jumped over the moon",   
                        "an apple a day keeps the doctor away",  
                        "four score and seven years ago",   
                        "snow white and the seven dwarfs",   
                        "i am at two with nature"};  
      String sentence = sentences[random.nextInt(sentences.length)];  
      collector.emit(new Values(sentence));  
  }