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. 操作AppConfig.xml中AppSettings对应值字符串

    //查询AppSettings的key         public static List sql()         {             List list = new List();   ...

  2. ASP.NET MVC进阶二

    一.数据验证 数据验证的步骤 在模型类中添加与验证相关的特性标记 在客户端导入与验证相关的js文件和css文件 使用与验证相关的Html辅助方法 在服务器端判断是否通过服务器端验证 常用的验证标记 R ...

  3. php中的常用数组函数(一)(比较多个数组的差集的函数们 array_diff_assoc() array_diff() array_diff_key() array_diff_ukey() array_diff_uassoc())

    array_diff_assoc($arr1, $arr2, $arr3,... n); 返回:一个$arr1的副本,后续的数组中出现一个键值相同的元素,就在副本中删掉这个元素,最后返回这个副本. 如 ...

  4. java int转byte和long转byte

    在网络编程中,出于节约带宽或者编码的需要,通常需要以原生方式处理long和int,而不是转换为string. public class ByteOrderUtils { public static b ...

  5. ASP.NET Web API默认支持的媒体类型(SupportedMediaTypes)

    JsonMediaTypeFormatter XmlMediaTypeFormatter ( application/xml  text/xml) FormUrlEncodedMediaTypeFor ...

  6. Oracle LPAD/RPAD函数在处理中文时的注意事项

    首先看下Oracle官方对函数的定义: The RPAD function returns an expression, right-padded to a specified length with ...

  7. 在cmd中获取ip地址和主机名

    将下面的文件放到一个bat文件当中,以管理员身份运行. @echo off &setlocal enabledelayedexpansion Rem '/*========获取本机的IP地址( ...

  8. 关于const和define的内存分配问题的总结

    关于const和define的内存分配问题 const与#define宏定义的区别----C语言深度剖析 1,  const定义的只读变量在程序运行过程中只有一份拷贝(因为它是全局的只读变量,存放在静 ...

  9. C中的一些经常会用到的函数

    1.sscanf 函数原型: int sscanf(const char *,const char *,...); int sscanf(const char *buffer,const char * ...

  10. iOS之UI--Quartz2D的入门应用--重绘下载圆形进度条

    *:first-child { margin-top: 0 !important; } body > *:last-child { margin-bottom: 0 !important; } ...