source code:

package stormdemo;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.StormSubmitter;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.topology.base.BaseBasicBolt;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values; public class WordCountTopology {
public static class WordReader extends BaseRichSpout {
private static final long serialVersionUID = 1L;
private SpoutOutputCollector collector;
private FileReader fileReader;
private boolean completed = false;
public void ack(Object msgId) {
System.out.println("OK:"+msgId);
}
public void close() {}
public void fail(Object msgId) {
System.out.println("FAIL:"+msgId);
}
/**The only thing that the methods will do It is emit each file line*/
public void nextTuple() {
/**
* The nextuple it is called forever, so if we have been readed the file
* we will wait and then return
*/
if(completed){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
//Do nothing
}
return;
}
String str;
//Open the reader
BufferedReader reader = new BufferedReader(fileReader);
try{
//Read all lines
while((str = reader.readLine()) != null){
/**
* By each line emmit a new value with the line as a their
*/
this.collector.emit(new Values(str),str);
}
}catch(Exception e){
throw new RuntimeException("Error reading tuple",e);
}finally{
completed = true;
}
} /**
* We will create the file and get the collector object
*/
public void open(@SuppressWarnings("rawtypes") Map conf, TopologyContext context,
SpoutOutputCollector collector) {
try {
this.fileReader = new FileReader(conf.get("wordsFile").toString());
} catch (FileNotFoundException e) {
throw new RuntimeException("Error reading file ["+conf.get("wordsFile")+"]");
}
this.collector = collector;
} /**
* Declare the output field "line"
*/
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("line"));
}
} public static class WordNormalizer extends BaseBasicBolt { private static final long serialVersionUID = 3L; public void cleanup() {}
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 bolt will only emit the field "word"
*/
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word"));
}
}
public static class WordCount extends BaseBasicBolt {
private static final long serialVersionUID = 2L;
Map<String, Integer> counts = new HashMap<String, Integer>();
BufferedWriter output = null;
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);
//collector.emit(new Values(word, count));
try {
output = new BufferedWriter(new FileWriter("/home/hadoop/wordcounts.txt",false ));
} catch (IOException e) {
e.printStackTrace();
try {
output.close();
} catch (IOException e1) { e1.printStackTrace(); }
}
for(Map.Entry<String, Integer> entry : counts.entrySet()){
try {
output.write(entry.getKey()+": "+entry.getValue());
output.newLine();
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word", "count"));
}
} public static void main(String[] args) throws Exception { TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("spout", new WordReader());
builder.setBolt("split", new WordNormalizer()).shuffleGrouping("spout");
builder.setBolt("count", new WordCount()).globalGrouping("split"); Config conf = new Config();
conf.put("wordsFile", args[0]);
conf.setDebug(false);
//Topology run
if (args != null && args.length > 1) {
conf.setNumWorkers(2);
StormSubmitter.submitTopology(args[1], conf, builder.createTopology());
}
else {
conf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, 1);
LocalCluster cluster = new LocalCluster();
cluster.submitTopology("wordcount", conf, builder.createTopology());
Thread.sleep(1000);
cluster.shutdown();
} }
}

start zookeeper.(zkServer.sh start at namenode,datanode01,datanode02)

start storm nimbus at namenode.

start storm supervisor at datanode01 and datanode02;

at namenode:

cd /home/hadoop/workspace

cd /stormsample

mvn install

storm jar storm-example-0.0.1-SNAPSHOT.jar stormdemo.WordCountTopology /home/hadoop/wordinput.txt wordcount

first, you should prepare text file for the source, I put one txt file wordinput.txt in datanode01 /02 /home/hadoop/.

after running job, I found wordcount.txt at datanode01 node.

Storm wordcount Read from file的更多相关文章

  1. 3、SpringBoot 集成Storm wordcount

    WordCountBolt public class WordCountBolt extends BaseBasicBolt { private Map<String,Integer> c ...

  2. [Storm] java.io.FileNotFoundException: File '../stormconf.ser' does not exist

    This bug will kill supervisors Affects Version/s: 0.9.2-incubating, 0.9.3, 0.9.4 Fix Version/s: 0.10 ...

  3. Storm WordCount

    特别注意,在本地运行的时候应该去掉<scope>provided</scope>,否则会报java.lang.ClassNotFoundException: org.apach ...

  4. Storm WordCount Topology学习

    1,分布式单词计数的流程 首先要有数据源,在SentenceSpout中定义了一个字符串数组sentences来模拟数据源.字符串数组中的每句话作为一个tuple发射.其实,SplitBolt接收Se ...

  5. Storm入门(四)WordCount示例

    一.关联代码 使用maven,代码如下. pom.xml  和Storm入门(三)HelloWorld示例相同 RandomSentenceSpout.java /** * Licensed to t ...

  6. 基于Storm的WordCount

    Storm WordCount 工作过程 Storm 版本: 1.Spout 从外部数据源中读取数据,随机发送一个元组对象出去: 2.SplitBolt 接收 Spout 中输出的元组对象,将元组中的 ...

  7. storm教程

    二.安装部署   一.storm伪分布式安装 (一)环境准备1.OS:debian 72.JDK 7.0 (二)安装zookeeper1.下载zookeeper并解压 wget http://mirr ...

  8. Storm之路-WordCount-实例

    初学storm,有不足的地方还请纠正. 网上看了很多wordcount实例,发现都不是我想要的. 实现场景:统计shengjing.txt词频到集合,一次打印结果. ● 消息源Spout 继承Base ...

  9. Storm实现单词计数

    package com.mengyao.storm; import java.io.File; import java.io.IOException; import java.util.Collect ...

随机推荐

  1. 创建Google网站地图Sitemap.xml

    Sitemap.xml是google搞出来的,也就是网站地图,不过这个网站地图是用xml写的,而且要按google的标准来写,并且要将写出来的这个文件sitemap.xml上传到自己的服务器空间中去. ...

  2. WCF小结

    WCF总结 1.WCF(原代号为Indigo)是一个用于创建和运行分布式系统的技术集合,使用它能创建安全的.可靠的.跨平台的的分布式解决方案.它的面向服务的编程模型,整合了.Net平台下以往全部的分布 ...

  3. SystemMenu类的用法

    先声明对象以及相应常数: //SystemMenu对象 private SystemMenu m_systemMenu = null; // ID 常数定义 (可变,只要不与系统冲突即可) priva ...

  4. 创建WCF服务寄宿到IIS

    一.WCF简介: Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以翻译为Windows 通讯开发平台. 整合了原有的win ...

  5. 【转载】delete table 和 truncate table 的区别

    使用delete语句删除数据的一般语法格式: delete [from] {table_name.view_name} [where] 将XS表中的所有行数据删除 delete XS 执行完后,发现X ...

  6. 【洛谷 p3386】模板-二分图匹配(图论)

    题目:给定一个二分图,结点个数分别为n,m,边数为e,求二分图最大匹配数. 解法:匈牙利算法.(以前我总是不记得......)实质上应该有贪心的思想,每次都尽量匹配,找到能和自己匹配的也尽量让它们匹配 ...

  7. Maven初步搭建 (一)

    什么是maven? 也许很多人开始的时候跟我一样,在看了很多工程之后都不知道这个鸟东西到底是用来干嘛用的!:-D 一个东西之所以会出现是有其原因的,譬如Linus大神写git. Maven项目对象模型 ...

  8. 爱你.一万年>>数据库基础

    嗨!最近学习了一项新的技能,学习了数据库的知识,在这里抛砖引玉,给大家说说,望赐教!!>> 01.首先给大家谈谈为什么要使用数据库? 数据库可以看成是一个永久保存数据的仓库. 可以存储大量 ...

  9. 我所了解的WEB开发(2) - PS切片

    PS对于WEB设计和前端开发来说都是不可或缺的工具,基本的用途是用来处理网站的LOGO.Banner 以及按钮图标来着,但是一旦遇上要把整个PSD文件转成网页就让人非常头痛了,可能还不太专业.后来在公 ...

  10. python基础(2)

    1.lambda函数 学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,函数同样有简单的表示方法 # ###################### 普通函数 ######### ...