storm中一个Bolt发emit多次相同类型消息

在storm中的Bolt中可以处理完成逻辑后,向后面的Blot继续发送消息。

可以发送多个不同的消息,如:

collector.emit("update-delivered-status",new Values(emailDeliverStatus));

collector.emit("save-request",new Values(udsn));


也可以同一个类型的消息发送多个不同内容如;

for (int i = 0; i < emailParamVo.getReceiverNum(); i++) 
			{
				EmailDeliverStatus emailDeliverStatus = new EmailDeliverStatus();
				emailDeliverStatus.setCategoryId(emailParamVo.getCategoryId());
				emailDeliverStatus.setUpdateTime(emailParamVo.getUpdateTime());
				emailDeliverStatus.setStatus(emailParamVo.getEventType());
				emailDeliverStatus.setUserId(emailParamVo.getUserId());
				emailDeliverStatus.setMessageDetail(emailParamVo.getMessageDetail());
				
				StringBuilder receiverBuilder = new StringBuilder(emailParamVo.getReceivers());
				receiverBuilder = receiverBuilder.deleteCharAt(0);
				receiverBuilder = receiverBuilder.deleteCharAt(receiverBuilder.length()-1);
				String[] receivers = receiverBuilder.toString().split(" ");
				String receiver = receivers[i];
				emailDeliverStatus.setEmailId(emailParamVo.getEmailIdPre() + i + "$" + receiver);
				emailDeliverStatus.setReceiver(receiver);
				collector.emit("update-delivered-status",new Values(emailDeliverStatus));
			}


上面的写法是没有问题的,因为for循环里面每次发送的对象都是一个新的实例,但是如果把创建实例的动作放到外面,如:

EmailDeliverStatus emailDeliverStatus = new EmailDeliverStatus();
			emailDeliverStatus.setCategoryId(emailParamVo.getCategoryId());
			emailDeliverStatus.setUpdateTime(emailParamVo.getUpdateTime());
			emailDeliverStatus.setStatus(emailParamVo.getEventType());
			emailDeliverStatus.setUserId(emailParamVo.getUserId());
			emailDeliverStatus.setMessageDetail(emailParamVo.getMessageDetail());
			
			for (int i = 0; i < emailParamVo.getReceiverNum(); i++) 
			{
				StringBuilder receiverBuilder = new StringBuilder(emailParamVo.getReceivers());
				receiverBuilder = receiverBuilder.deleteCharAt(0);
				receiverBuilder = receiverBuilder.deleteCharAt(receiverBuilder.length()-1);
				String[] receivers = receiverBuilder.toString().split(" ");
				String receiver = receivers[i];
				emailDeliverStatus.setEmailId(emailParamVo.getEmailIdPre() + i + "$" + receiver);
				emailDeliverStatus.setReceiver(receiver);
				collector.emit("update-delivered-status",new Values(emailDeliverStatus));
			}


 

这样就有问题,按照逻辑,我们是想让其emit多个不同emailDeliverStatus对象的消息,但是实际上这样不不行的,因为storm的emit操作并不是立即执行的,

上面的代码就是建立在假设调用emit后,storm就会立即去发送消息。如果按照上面写法,会发现接收消息的bolt收到的for循环中的多个消息都是最后一个消息的重复多次。

因为storm并不是立即执行emit,而是在这个bolt执行的一个固定时间去emit的,所以emailDeliverStatus实例的初始化必须放到for循环的外面执行。

你可能感兴趣的:(大数据)