STORM入门之(TridentAPI,Each)

1.基础

基础Topology与TritentTopology是不同的,就相当于JDBC VS Hibernate  ,Hibernate是基于JDBC实现的ORM架构,二者本质是相同的,但是用法截然不同,Trident会抽象一些,不过底层也是基于Topology的Spout,Bolt等基础来构建,并且最终提交任务时,TritentTopology是会转换成Topology。Each相当于把Spout分割成段,进行batch处理。Each方法包含过滤函数方式进行流式处理,下面代码是针对filter与function进行编写

2.代码

下面是简单构建TritentTopology的代码

 public static void main(String[] args){
        TridentTopology topology = new TridentTopology();
        FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 1,
                new Values("the cow jumped over the moon"),
                new Values("the man went to the store and bought some candy"),
                new Values("four score and seven years ago"),
                new Values("how many apples can you eat"));
        spout.setCycle(true);
        topology.newStream("batch-spout",spout)
                .each(new Fields("sentence"), new Split(), new Fields("word"))
                .each(new Fields("sentence","word"), new WordFilter("the"));
        StormTopology stormTopology = topology.build();
        LocalCluster cluster = new LocalCluster();
        Config conf = new Config();
        conf.setDebug(true);
        cluster.submitTopology("soc", conf,stormTopology);
    }

Function分割函数Split

package com.storm.trident;

import org.apache.storm.trident.operation.BaseFunction;
import org.apache.storm.trident.operation.TridentCollector;
import org.apache.storm.trident.tuple.TridentTuple;
import org.apache.storm.tuple.Values;

public class Split extends BaseFunction {
    public void execute(TridentTuple tuple, TridentCollector collector) {
        String sentence = tuple.getString(0);
        for(String word: sentence.split(" ")) {
            System.out.println("emit word is :"+word);
            collector.emit(new Values(word));
        }
    }
}


Filter过滤

package com.storm.trident;

import org.apache.storm.trident.operation.BaseFilter;
import org.apache.storm.trident.tuple.TridentTuple;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 17-9-1
 * Time: 上午9:03
 * To change this template use File | Settings | File Templates.
 */
public class WordFilter extends BaseFilter {

    String actor;
    public WordFilter(String actor) {
        this.actor = actor;
    }

    @Override
    public boolean isKeep(TridentTuple tuple) {
        if(tuple.getString(1).equals(actor)){
            System.out.println("Filter word is:"+tuple.getString(1) + "  and return type is:"+tuple.getString(1).equals(actor));
        }
        return tuple.getString(1).equals(actor);
    }
}

运行结果




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值