Storm wordcount Read from file
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的更多相关文章
- 3、SpringBoot 集成Storm wordcount
WordCountBolt public class WordCountBolt extends BaseBasicBolt { private Map<String,Integer> c ...
- [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 ...
- Storm WordCount
特别注意,在本地运行的时候应该去掉<scope>provided</scope>,否则会报java.lang.ClassNotFoundException: org.apach ...
- Storm WordCount Topology学习
1,分布式单词计数的流程 首先要有数据源,在SentenceSpout中定义了一个字符串数组sentences来模拟数据源.字符串数组中的每句话作为一个tuple发射.其实,SplitBolt接收Se ...
- Storm入门(四)WordCount示例
一.关联代码 使用maven,代码如下. pom.xml 和Storm入门(三)HelloWorld示例相同 RandomSentenceSpout.java /** * Licensed to t ...
- 基于Storm的WordCount
Storm WordCount 工作过程 Storm 版本: 1.Spout 从外部数据源中读取数据,随机发送一个元组对象出去: 2.SplitBolt 接收 Spout 中输出的元组对象,将元组中的 ...
- storm教程
二.安装部署 一.storm伪分布式安装 (一)环境准备1.OS:debian 72.JDK 7.0 (二)安装zookeeper1.下载zookeeper并解压 wget http://mirr ...
- Storm之路-WordCount-实例
初学storm,有不足的地方还请纠正. 网上看了很多wordcount实例,发现都不是我想要的. 实现场景:统计shengjing.txt词频到集合,一次打印结果. ● 消息源Spout 继承Base ...
- Storm实现单词计数
package com.mengyao.storm; import java.io.File; import java.io.IOException; import java.util.Collect ...
随机推荐
- php Calender(日历)代码
代码如下: <?php /** * * 我的日历 * date_default_timezone_set date mktime * @param int $year * @param int ...
- 与众不同 windows phone (35) - 8.0 新的启动器: ShareMediaTask, SaveAppointmentTask, MapsTask, MapsDirectionsTask, MapDownloaderTask
[源码下载] 与众不同 windows phone (35) - 8.0 新的启动器: ShareMediaTask, SaveAppointmentTask, MapsTask, MapsDirec ...
- mybatis中自建的类型别名
在使用mybatis过程中经常用到类型别名,除了我们自己新建的别名外,mybatis还自带了很多类型别名和java中的类型的映射,下面先看一个自建的别名的配置 <typeAliases> ...
- 1秒30000QPS,前后端设计思路
Q:现在有这样一个需求,在一秒中有3万的支付订单请求,有什么比较好的解决方案吗? PS:我们数据库用的是oracle 程序是java spring mybatis dubbo mq等技术,现在有这样一 ...
- mysql performance_schema/information_schema授权问题
mysql> grant all on performance_schema.* to 'testuser'@'%';ERROR 1044 (42000): Access denied for ...
- android布局--Android fill_parent、wrap_content和match_parent的区别
来自:http://www.cnblogs.com/nikyxxx/archive/2012/06/15/2551390.html 三个属性都用来适应视图的水平或垂直大小,一个以视图的内容或尺寸为基础 ...
- SharePoint 使用PowerShell恢复误删的网站集
在SharePoint网站集的使用中,我们很有可能会误删我们需要的网站集,SharePoint其实并没有把网站集删掉,只是放到了SPDeletedSite中,这样,我们还可以通过PowerShell找 ...
- SharePoint 使用代码为页面添加WebPart
传统的SharePoint实施中,我们通常会创建SharePoint页面,然后添加webpartzone,而后在上面添加webpart:但是有些情况下,也要求我们使用代码,将webpart添加到相应w ...
- [ html canvas putImageData ] canvas绘图属性 putImageData 属性讲解
<!DOCTYPE html> <html lang='zh-cn'> <head> <title>Insert you title</title ...
- SharePoint 2013中Office Web Apps的一次排错
转自http://www.cnblogs.com/awpatp/archive/2013/06/06/3121420.html, 仅供自己查看 笔者尝试在自己的测试环境中为SharePoint 201 ...