转载请注明出处:http://blog.csdn.net/luonanqin
最近研究Storm的Stream Grouping的时候,对Field Grouping和Shuffle Grouping理解不是很透彻。去看WordCountTopology也不怎么理解,后来脑洞一开,加了一行代码再次运行,彻底顿悟。只能说自己对Storm的基本概念还是没吃透啊。(WordCountTopology这个例子请自行参考Storm-Starter)
public void execute(Tuple tuple, BasicOutputCollector collector) {
	String word = tuple.getString(0);
	// 添加这行代码的作用是看看值相等的word是不是同一个实例执行的,实时证明确实如此
	System.out.println(this + "====" + word);
	
	Integer count = counts.get(word);
	if (count == null)
		count = 0;
	count++;
	counts.put(word, count);
	collector.emit(new Values(word, count));
}经过反复测试,下面是我个人的一些总结,如果有缺少或者错误我会及时改正。
官方文档里有这么一句话:“if the stream is grouped by the “user-id” field, tuples with the same “user-id” will always go to the same task”
一个task就是一个处理逻辑的实例,所以fields能根据tuple stream的id,也就是下面定义的xxx
public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("xxx"));
}xxx所代表的具体内容会由某一个task来处理,并且同一个xxx对应的内容,处理这个内容的task实例是同一个。
比如说:
bolt第一次emit三个流,即xxx有luonq pangyang qinnl三个值,假设分别建立三个task实例来处理:
luonq -> instance1
pangyang -> instance2
qinnl -> instance3然后第二次emit四个流,即xxx有luonq qinnanluo py pangyang四个值,假设还是由刚才的三个task实例来处理:
luonq -> instance1
qinnanluo -> instance2
py -> instance3
pangyang -> instance2
   然后第三次emit两个流,即xxx有py qinnl两个值,假设还是由刚才的三个task实例来处理:
   
py -> instance3
qinnl -> instance3最后我们看看三个task实例都处理了哪些值,分别处理了多少次:
   instance1: luonq(处理2次)
   
   instance2: pangyang(处理2次) qinnanluo(处理1次)
   
   instance3: qinnl(处理2次) py(处理2次)
   结论:
   
   1. emit发出的值第一次由哪个task实例处理是随机的,此后再次出现这个值,就固定由最初处理他的那个task实例再次处理,直到topology结束
2. 一个task实例可以处理多个emit发出的值
   3. 和shuffle Grouping的区别就在于,当emit发出同样的值时,处理他的task是随机的
   
 
