Storm實戰之TopN

541732025發表於2015-04-16
TopN這種統計場景很常見,例如,統計出搜尋熱度最高的詞,點選率最高的廣告等,現在有了Hadoop、Storm這些工具之後,很方便地就能得到結果。
這裡以Storm為例,簡易地實現了TopN單詞的統計,由於剛剛入門,程式碼寫得比較簡單。
首先,在多臺機器上執行多個bolt,每個bolt負責計算一部分word的TopN,最後有一個全域性的bolt,合併上一步的結果,最後得出全域性的TopN。

點選(此處)摺疊或開啟

  1. package test.storm.topology;

  2. import test.storm.bolt.WordCounter;
  3. import test.storm.bolt.WordWriter;
  4. import test.storm.spout.WordReader;
  5. import backtype.storm.Config;
  6. import backtype.storm.StormSubmitter;
  7. import backtype.storm.generated.AlreadyAliveException;
  8. import backtype.storm.generated.InvalidTopologyException;
  9. import backtype.storm.topology.TopologyBuilder;
  10. import backtype.storm.tuple.Fields;

  11. public class WordTopN {
  12.     public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException {
  13.         if (args == null || args.length < 1) {
  14.             System.err.println("Usage: N");
  15.             System.err.println("such as : 10");
  16.             System.exit(-1);
  17.         }

  18.         TopologyBuilder builder = new TopologyBuilder();
  19.         builder.setSpout("wordreader", new WordReader(), 2);
  20.         builder.setBolt("wordcounter", new WordCounter(), 2).fieldsGrouping("wordreader", new Fields("word"));
  21.         builder.setBolt("wordwriter", new WordWriter()).globalGrouping("wordcounter");

  22.         Config conf = new Config();
  23.         conf.put("N", args[0]);

  24.         conf.setDebug(false);
  25.         StormSubmitter.submitTopology("topN", conf, builder.createTopology());

  26.     }
  27. }
這裡需要注意的幾點是,第一個bolt的分組策略是fieldsGrouping,按照欄位分組,這一點很重要,它能保證相同的word被分發到同一個bolt上,
像做wordcount、TopN之類的應用就要使用這種分組策略。
最後一個bolt的分組策略是globalGrouping,全域性分組,tuple會被分配到一個bolt用來彙總。
為了提高並行度,spout和第一個bolt均設定並行度為2(我這裡測試機器效能不是很高)。

點選(此處)摺疊或開啟

  1. package test.storm.spout;

  2. import java.util.Map;
  3. import java.util.Random;
  4. import java.util.concurrent.atomic.AtomicInteger;

  5. import backtype.storm.spout.SpoutOutputCollector;
  6. import backtype.storm.task.TopologyContext;
  7. import backtype.storm.topology.OutputFieldsDeclarer;
  8. import backtype.storm.topology.base.BaseRichSpout;
  9. import backtype.storm.tuple.Fields;
  10. import backtype.storm.tuple.Values;

  11. public class WordReader extends BaseRichSpout {
  12.     private static final long serialVersionUID = 2197521792014017918L;
  13.     private SpoutOutputCollector collector;
  14.     private static AtomicInteger i = new AtomicInteger();
  15.     private static String[] words = new String[] { \"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\",
  16.             \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\" };

  17.     @Override
  18.     public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
  19.         this.collector = collector;
  20.     }

  21.     @Override
  22.     public void nextTuple() {
  23.         if (i.intValue() < 100) {
  24.             Random rand = new Random();
  25.             String word = words[rand.nextInt(words.length)];
  26.             collector.emit(new Values(word));
  27.             i.incrementAndGet();
  28.         }
  29.     }

  30.     @Override
  31.     public void declareOutputFields(OutputFieldsDeclarer declarer) {
  32.         declarer.declare(new Fields("word"));
  33.     }
  34. }
spout的作用是隨機傳送word,傳送100次,由於並行度是2,將產生2個spout例項,所以這裡的計數器使用了static的AtomicInteger來保證執行緒安全。


點選(此處)摺疊或開啟

  1. package test.storm.bolt;

  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Map.Entry;
  9. import java.util.concurrent.ConcurrentHashMap;

  10. import backtype.storm.task.OutputCollector;
  11. import backtype.storm.task.TopologyContext;
  12. import backtype.storm.topology.IRichBolt;
  13. import backtype.storm.topology.OutputFieldsDeclarer;
  14. import backtype.storm.tuple.Fields;
  15. import backtype.storm.tuple.Tuple;
  16. import backtype.storm.tuple.Values;

  17. public class WordCounter implements IRichBolt {
  18.     private static final long serialVersionUID = 5683648523524179434L;
  19.     private static Map<String, Integer> counters = new ConcurrentHashMap<String, Integer>();
  20.     private volatile boolean edit = true;

  21.     @Override
  22.     public void prepare(final Map stormConf, TopologyContext context, final OutputCollector collector) {
  23.         new Thread(new Runnable() {
  24.             @Override
  25.             public void run() {
  26.                 while (true) {
  27.                     //5秒後counter不再變化,可以認為spout已經傳送完畢
  28.                     if (!edit) {
  29.                         if (counters.size() > 0) {
  30.                             List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>();
  31.                             list.addAll(counters.entrySet());
  32.                             Collections.sort(list, new ValueComparator());

  33.                             //向下一個bolt傳送前N個word
  34.                             for (int i = 0; i < list.size(); i++) {
  35.                                 if (i < Integer.parseInt(stormConf.get("N").toString())) {
  36.                                     collector.emit(new Values(list.get(i).getKey() + ":" + list.get(i).getValue()));
  37.                                 }
  38.                             }
  39.                         }

  40.                         //傳送之後,清空counters,以防spout再次傳送word過來
  41.                         counters.clear();
  42.                     }

  43.                     edit = false;
  44.                     try {
  45.                         Thread.sleep(5000);
  46.                     } catch (InterruptedException e) {
  47.                         e.printStackTrace();
  48.                     }
  49.                 }
  50.             }
  51.         }).start();
  52.     }

  53.     @Override
  54.     public void execute(Tuple tuple) {
  55.         String str = tuple.getString(0);
  56.         if (counters.containsKey(str)) {
  57.             Integer c = counters.get(str) + 1;
  58.             counters.put(str, c);
  59.         } else {
  60.             counters.put(str, 1);
  61.         }

  62.         edit = true;
  63.     }

  64.     private static class ValueComparator implements Comparator<Map.Entry<String, Integer>> {
  65.         @Override
  66.         public int compare(Entry<String, Integer> entry1, Entry<String, Integer> entry2) {
  67.             return entry2.getValue() - entry1.getValue();
  68.         }
  69.     }

  70.     @Override
  71.     public void declareOutputFields(OutputFieldsDeclarer declarer) {
  72.         declarer.declare(new Fields("word_count"));
  73.     }

  74.     @Override
  75.     public void cleanup() {
  76.     }

  77.     @Override
  78.     public Map<String, Object> getComponentConfiguration() {
  79.         return null;
  80.     }
  81. }
在WordCounter裡面有個執行緒安全的容器ConcurrentHashMap,來儲存word以及對應的次數。在prepare方法裡啟動一個執行緒,長期監聽edit的狀態,監聽間隔是5秒,
當edit為false,即execute方法不再執行、容器不再變化,可以認為spout已經傳送完畢了,可以開始排序取TopN了。這裡使用了一個volatile edit(回憶一下volatile的使用場景:
對變數的修改不依賴變數當前的值,這裡設定true or false,顯然不相互依賴)。


點選(此處)摺疊或開啟

  1. package test.storm.bolt;

  2. import java.io.FileWriter;
  3. import java.io.IOException;
  4. import java.util.Map;

  5. import backtype.storm.task.TopologyContext;
  6. import backtype.storm.topology.BasicOutputCollector;
  7. import backtype.storm.topology.OutputFieldsDeclarer;
  8. import backtype.storm.topology.base.BaseBasicBolt;
  9. import backtype.storm.tuple.Tuple;

  10. public class WordWriter extends BaseBasicBolt {
  11.     private static final long serialVersionUID = -6586283337287975719L;
  12.     private FileWriter writer = null;

  13.     public WordWriter() {
  14.     }

  15.     @Override
  16.     public void prepare(Map stormConf, TopologyContext context) {
  17.         try {
  18.             writer = new FileWriter("/data/tianzhen/output/" + this);
  19.         } catch (IOException e) {
  20.             e.printStackTrace();
  21.         }
  22.     }

  23.     @Override
  24.     public void execute(Tuple input, BasicOutputCollector collector) {
  25.         String s = input.getString(0);
  26.         try {
  27.             writer.write(s);
  28.             writer.write("\n");
  29.             writer.flush();
  30.         } catch (IOException e) {
  31.             e.printStackTrace();
  32.         } finally {
  33.             //writer不能close,因為execute需要一直執行
  34.         }
  35.     }

  36.     @Override
  37.     public void declareOutputFields(OutputFieldsDeclarer declarer) {

  38.     }
  39. }
最後一個bolt做全域性的彙總,這裡我偷了懶,直接將結果寫到檔案了,省略擷取TopN的過程,因為我這裡就一個supervisor節點,所以結果是正確的。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28912557/viewspace-1579860/,如需轉載,請註明出處,否則將追究法律責任。

相關文章