Custom Grouping

2021SC@SDUSC

public interface CustomStreamGrouping extends Serializable {
 
    /**
     * Tells the stream grouping at runtime the tasks in the target bolt. This information should be used in chooseTasks to determine the
     * target tasks.
     *
     * It also tells the grouping the metadata on the stream this grouping will be used on.
     */
    void prepare(WorkerTopologyContext context, GlobalStreamId stream, List<Integer> targetTasks);
 
    /**
     * This function implements a custom stream grouping. It takes in as input the number of tasks in the target bolt in prepare and returns
     * the tasks to send the tuples to.
     *
     * @param values the values to group on
     */
    List<Integer> chooseTasks(int taskId, List<Object> values);
}

实现backtype.storm.grouping.CustomStreamGrouping接口即可完成用户自定义Grouping

例如:单次计数按照第一单词的第一个字母mod task数的余数来分配

package CostumerGroup;
 
import backtype.storm.grouping.CustomStreamGrouping;
import backtype.storm.task.TopologyContext;
import backtype.storm.tuple.Fields;
 
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
 
/**
 * Created by hjw on 17/5/26.
 */
public class ModuleGrouping implements CustomStreamGrouping {//,Serializable
    int numTasks = 0;
    private List<Integer>  targetTasks;
 
    @Override
    public void prepare(TopologyContext topologyContext, Fields fields, List<Integer> targetTasks) {
        numTasks =  targetTasks.size();
        this.targetTasks = targetTasks;
    }
    @Override
    public List<Integer> chooseTasks(List<Object> values) {
        List<Integer> boltIDs = new ArrayList<Integer>();
        if(values.size() >0 ){
            String str = values.get(0).toString();
            if (str.isEmpty())
                boltIDs.add(targetTasks.get(0));
            else
                boltIDs.add(targetTasks.get((int)(str.charAt(0))%numTasks));//根据余数分配
        }
        return boltIDs;
    }
}
	builder.setBolt("word-normalizer", new WordNormalizer()).
				customGrouping("word-reader", new ModuleGrouping());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值