Storm Experiment--word Count 4

Source: Internet
Author: User

On the basis of the previous word count, make the following changes: Use the custom Group Policy to send words with the same initial letter to the same task count

Custom Customstreamgrouping
Package Com.zhch.v4;import Backtype.storm.generated.globalstreamid;import Backtype.storm.grouping.customstreamgrouping;import Backtype.storm.task.workertopologycontext;import Java.io.serializable;import Java.util.arraylist;import Java.util.list;public class Modulegrouping implements    Customstreamgrouping, Serializable {private list<integer> tasks; @Override public void Prepare (Workertopologycontext workercontext, Globalstreamid streamid, list<integer> target    Tasks) {this.tasks = Targettasks; } @Override public list<integer> choosetasks (int taskId, list<object> values) {LIST&LT;INTEGER&G T        Taskids = new arraylist<integer> ();            if (values.size () > 0) {String str = values.get (0). toString ();            if (Str.isempty ()) {taskids.add (0);                } else {Integer index = str.charat (0)% tasks.size ();            Taskids.add (Tasks.get (index)); }} REturn Taskids; }}

data source spout

Package Com.zhch.v4;import Backtype.storm.spout.spoutoutputcollector;import Backtype.storm.task.TopologyContext; Import Backtype.storm.topology.outputfieldsdeclarer;import Backtype.storm.topology.base.baserichspout;import Backtype.storm.tuple.fields;import Backtype.storm.tuple.values;import Java.io.bufferedreader;import Java.io.filereader;import Java.util.map;import Java.util.uuid;import Java.util.concurrent.ConcurrentHashMap;    public class Sentencespout extends Baserichspout {private FileReader filereader = null;    Private Boolean completed = false;    Private Concurrenthashmap<uuid, values> pending;    Private Spoutoutputcollector collector; @Override public void Declareoutputfields (Outputfieldsdeclarer outputfieldsdeclarer) {outputfieldsdeclarer.decl    Is (new fields ("sentence"));        } @Override public void open (map map, Topologycontext Topologycontext, Spoutoutputcollector spoutoutputcollector) {        This.collector = Spoutoutputcollector; This.penDing = new Concurrenthashmap<uuid, values> ();        try {this.filereader = new FileReader (Map.get ("Wordsfile"). toString ());        } catch (Exception e) {throw new RuntimeException ("Error reading file [" + Map.get ("wordsfile") + "]"); }} @Override public void Nexttuple () {if (completed) {try {Thread.Sleep (10            00);        } catch (Interruptedexception e) {}} String line;        BufferedReader reader = new BufferedReader (FileReader);                try {while (line = Reader.readline ())! = null) {Values values = new values (line);                UUID msgId = Uuid.randomuuid ();                This.pending.put (msgId, values);            This.collector.emit (values, msgId);        }} catch (Exception e) {throw new RuntimeException ("Error reading tuple", e);        } finally {completed = true;    }} @Overridepublic void Ack (Object msgId) {this.pending.remove (msgId);    } @Override public void fail (Object msgId) {this.collector.emit (This.pending.get (msgId), msgId); }}

implement statement split Bolt

Package Com.zhch.v4;import Backtype.storm.task.outputcollector;import Backtype.storm.task.topologycontext;import Backtype.storm.topology.outputfieldsdeclarer;import Backtype.storm.topology.base.baserichbolt;import Backtype.storm.tuple.fields;import Backtype.storm.tuple.tuple;import Backtype.storm.tuple.values;import    Java.util.map;public class Splitsentencebolt extends Baserichbolt {private Outputcollector collector; @Override public void prepare (map map, Topologycontext Topologycontext, Outputcollector outputcollector) {this.    Collector = Outputcollector;        } @Override public void execute (tuple tuple) {String sentence = Tuple.getstringbyfield ("sentence");        string[] Words = Sentence.split ("");        for (String word:words) {collector.emit (tuple, new Values (word));    } this.collector.ack (tuple); } @Override public void Declareoutputfields (Outputfieldsdeclarer outputfieldsdeclarer) {Outputfieldsdeclarer . declIs (new fields ("word")); }}

implements the word count bolt 

Package Com.zhch.v4;import Backtype.storm.task.outputcollector;import Backtype.storm.task.topologycontext;import Backtype.storm.topology.outputfieldsdeclarer;import Backtype.storm.topology.base.baserichbolt;import Backtype.storm.tuple.fields;import Backtype.storm.tuple.tuple;import Java.io.bufferedwriter;import Java.io.filewriter;import Java.util.arraylist;import Java.util.collections;import Java.util.HashMap;import Java.util.list;import Java.util.map;public class Wordcountbolt extends Baserichbolt {private Outputcollector collector    ;    Private Hashmap<string, long> counts = null; @Override public void prepare (map map, Topologycontext Topologycontext, Outputcollector outputcollector) {this.        Collector = Outputcollector;    this.counts = new hashmap<string, long> ();        } @Override public void execute (tuple tuple) {String word = Tuple.getstringbyfield ("word");        Long count = This.counts.get (word); if (count = = null) {COunt = 0L;        } count++;        This.counts.put (Word, count);        BufferedWriter writer = null;            try {writer = new BufferedWriter (New FileWriter ("/home/grid/stormdata/result.txt"));            list<string> keys = new arraylist<string> ();            Keys.addall (This.counts.keySet ());            Collections.sort (keys);                for (String Key:keys) {Long c = this.counts.get (key);                Writer.write (key + ":" + C);                Writer.newline ();            Writer.flush ();        }} catch (Exception e) {e.printstacktrace ();                } finally {if (writer! = null) {try {writer.close ();                } catch (Exception e) {e.printstacktrace ();            } writer = null;    }} this.collector.ack (tuple); } @Override public void Declareoutputfields (Outputfieldsdeclarer outpUtfieldsdeclarer) {Outputfieldsdeclarer.declare (New fields ("word", "count")); }}

implements the word count topology 

Package Com.zhch.v4;import Backtype.storm.config;import Backtype.storm.localcluster;import    Backtype.storm.stormsubmitter;import Backtype.storm.topology.topologybuilder;public class WordCountTopology {    public static final String sentence_spout_id = "Sentence-spout";    public static final String split_bolt_id = "Split-bolt";    public static final String count_bolt_id = "Count-bolt";    public static final String topology_name = "Word-count-topology-v4";        public static void Main (string[] args) throws Exception {sentencespout spout = new Sentencespout ();        Splitsentencebolt Spiltbolt = new Splitsentencebolt ();        Wordcountbolt Countbolt = new Wordcountbolt ();        Topologybuilder builder = new Topologybuilder ();        Builder.setspout (sentence_spout_id, SPOUT, 2);        Builder.setbolt (split_bolt_id, Spiltbolt, 2). Setnumtasks (4). shufflegrouping (sentence_spout_id); Builder.setbolt (count_bolt_id, Countbolt, 2). Customgrouping (split_bolt_id, New modulegrouping ());        Use the custom grouping policy config config = new config ();        Config.put ("Wordsfile", Args[0]);            if (args! = null && args.length > 1) {config.setnumworkers (2);        Cluster mode start Stormsubmitter.submittopology (args[1], config, builder.createtopology ());            } else {Localcluster cluster = new Localcluster ();            Cluster.submittopology (topology_name, config, builder.createtopology ());            try {thread.sleep (5 * 1000);            } catch (Interruptedexception e) {} cluster.killtopology (topology_name);        Cluster.shutdown (); }    }}

submit to Storm cluster

Storm Jar Storm02-1.0-snapshot.jar Com.zhch.v4.wordcounttopology/home/grid/stormdata/input.txt Word-count-topology-v4

Operation Result:

[email protected] stormdata]$ cat Result.txt Apache:1etl:1it:1storm:4a:4analytics:1and:5any:1at:1can:  1cases:: 1clocked:1computation:2continuous:1easy:2guarantees:1is:6it:2machine:1makes:1many:1million: 1more:1of:2online:1open:1operate:1over:1scalable:1second:1set:1simple:1source:1streams:1system: 1unbounded:1up:1use:2used:1what:1will:1with:1your:1[[email protected] stormdata]$ cat Result.txt Hadoop:  1rpc:1batch:1be:2benchmark:1data:2did:1distributed:2doing:1fast:: 1fault-tolerant:1for:2free:1fun: 1has:1language:1learning:1lot:1node:1per:2process:1processed:2processing:2programming:1realtime:3re Liably:1to:3torm:1tuples:1


Storm Experiment--word Count 4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.