Updated on 2022-08-16 GMT+08:00

Creating a Bolt

Function Description

All message processing logic is encapsulated in Bolts. Bolts provide multiple functions, such as filtering and aggregation.

If other topology operators, except for Bolts, exist, OutputFieldsDeclarer.declareStream can be used to define streams, and OutputCollector.emit can be used to select streams to be emitted.

Code Sample

The following code snippet belongs to the execute method in the SplitSentenceBolt class of the com.huawei.storm.example.common package, and these code snippets are used to split a statement into words and send the words.

/** 
  * {@inheritDoc} 
  */ 
 @Override 
 public void execute(Tuple input, BasicOutputCollector collector) 
 { 
     String sentence = input.getString(0); 
     String[] words = sentence.split(" "); 
     for (String word : words) 
     { 
         word = word.trim(); 
         if (!word.isEmpty()) 
         { 
             word = word.toLowerCase(); 
             collector.emit(new Values(word)); 
         } 
     } 
 }

The following code snippets are in the com.huawei.storm.example.wordcount.WordCountBolt class, and these code snippets are used to calculate the number of received words.

    @Override  
     public void execute(Tuple tuple, BasicOutputCollector collector)  
     {  
         String word = tuple.getString(0);  
         Integer count = counts.get(word);  
         if (count == null)  
         {  
             count = 0;  
         }  
         count++;  
         counts.put(word, count);  
         System.out.println("word: " + word + ", count: " + count);  
     }