backtype.storm.LocalDRPC Java Examples

The following examples show how to use backtype.storm.LocalDRPC. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TridentWordCount.java    From flink-perf with Apache License 2.0 7 votes vote down vote up
public static StormTopology buildTopology(LocalDRPC drpc) {
  FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3, 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"), new Values("to be or not to be the person"));
  spout.setCycle(true);

  TridentTopology topology = new TridentTopology();
  TridentState wordCounts = topology.newStream("spout1", spout).parallelismHint(16).each(new Fields("sentence"),
      new Split(), new Fields("word")).groupBy(new Fields("word")).persistentAggregate(new MemoryMapState.Factory(),
      new Count(), new Fields("count")).parallelismHint(16);

  topology.newDRPCStream("words", drpc).each(new Fields("args"), new Split(), new Fields("word")).groupBy(new Fields(
      "word")).stateQuery(wordCounts, new Fields("word"), new MapGet(), new Fields("count")).each(new Fields("count"),
      new FilterNull()).aggregate(new Fields("count"), new Sum(), new Fields("sum"));
  return topology.build();
}
 
Example #2
Source File: Part04_BasicStateAndDRPC.java    From trident-tutorial with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception{
        FakeTweetGenerator fakeTweets = new FakeTweetGenerator();
        FeederBatchSpout testSpout = new FeederBatchSpout(ImmutableList.of("id", "text", "actor", "location", "date"));

        Config conf = new Config();
        LocalCluster cluster = new LocalCluster();
        LocalDRPC drpc = new LocalDRPC();
        cluster.submitTopology("state_drpc", conf, basicStateAndDRPC(drpc, testSpout));

        // You can use FeederBatchSpout to feed known values to the topology. Very useful for tests.
        testSpout.feed(fakeTweets.getNextTweetTuples("ted"));
        testSpout.feed(fakeTweets.getNextTweetTuples("ted"));
        testSpout.feed(fakeTweets.getNextTweetTuples("mary"));
        testSpout.feed(fakeTweets.getNextTweetTuples("jason"));

        // This is how you make DRPC calls. First argument must match the function name
        // System.out.println(drpc.execute("ping", "ping pang pong"));
        // System.out.println(drpc.execute("count", "america america ace ace ace item"));
        System.out.println(drpc.execute("count_per_actor", "ted"));
        // System.out.println(drpc.execute("count_per_actors", "ted mary pere jason"));

        // You can use a client library to make calls remotely
//        DRPCClient client = new DRPCClient("drpc.server.location", 3772);
//        System.out.println(client.execute("ping", "ping pang pong"));
    }
 
Example #3
Source File: TridentMinMaxOfVehiclesTopology.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static void test() {
    TopologyBuilder builder = new TopologyBuilder();
    
    builder.setSpout("spout", new InOrderSpout(), 8);
    builder.setBolt("count", new Check(), 8).fieldsGrouping("spout", new Fields("c1"));
    
    conf.setMaxSpoutPending(20);
    
    String[] className = Thread.currentThread().getStackTrace()[1].getClassName().split("\\.");
    String topologyName = className[className.length - 1];
    
    if (isLocal) {
        drpc = new LocalDRPC();
    }
    
    try {
        JStormHelper.runTopology(buildVehiclesTopology(), topologyName, conf, 60,
                new JStormHelper.CheckAckedFail(conf), isLocal);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Assert.fail("Failed");
    }
}
 
Example #4
Source File: TridentReach.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static void test() {
    TopologyBuilder builder = new TopologyBuilder();
    
    builder.setSpout("spout", new InOrderSpout(), 8);
    builder.setBolt("count", new Check(), 8).fieldsGrouping("spout", new Fields("c1"));
    
    conf.setMaxSpoutPending(20);
    
    String[] className = Thread.currentThread().getStackTrace()[1].getClassName().split("\\.");
    String topologyName = className[className.length - 1];
    
    if (isLocal) {
        drpc = new LocalDRPC();
    }
    
    try {
        JStormHelper.runTopology(buildTopology(drpc), topologyName, conf, 60, new DrpcValidator(), isLocal);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Assert.fail("Failed");
    }
}
 
Example #5
Source File: TridentMapExample.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static void test() {
    TopologyBuilder builder = new TopologyBuilder();
    
    builder.setSpout("spout", new InOrderSpout(), 8);
    builder.setBolt("count", new Check(), 8).fieldsGrouping("spout", new Fields("c1"));
    
    Config conf = new Config();
    conf.setMaxSpoutPending(20);
    
    String[] className = Thread.currentThread().getStackTrace()[1].getClassName().split("\\.");
    String topologyName = className[className.length - 1];
    
    if (isLocal) {
        drpc = new LocalDRPC();
    }
    
    try {
        JStormHelper.runTopology(buildTopology(drpc), topologyName, conf, 60, new DrpcValidator(), isLocal);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Assert.fail("Failed");
    }
}
 
Example #6
Source File: TridentMapExample.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static StormTopology buildTopology(LocalDRPC drpc) {
    FixedBatchSpout spout = new FixedBatchSpout(new Fields("word"), 3, 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"),
            new Values("to be or not to be the person"));
    spout.setCycle(true);
    
    TridentTopology topology = new TridentTopology();
    TridentState wordCounts = topology.newStream("spout1", spout).parallelismHint(16).flatMap(split).map(toUpper)
            .filter(theFilter).peek(new Consumer() {
                @Override
                public void accept(TridentTuple input) {
                    System.out.println(input.getString(0));
                }
            }).groupBy(new Fields("word"))
            .persistentAggregate(new MemoryMapState.Factory(), new Count(), new Fields("count"))
            .parallelismHint(16);
            
    topology.newDRPCStream("words", drpc).flatMap(split).groupBy(new Fields("args"))
            .stateQuery(wordCounts, new Fields("args"), new MapGet(), new Fields("count")).filter(new FilterNull())
            .aggregate(new Fields("count"), new Sum(), new Fields("sum"));
    return topology.build();
}
 
Example #7
Source File: TridentWordCount.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static void test() {
    
    conf.setMaxSpoutPending(20);
    
    String[] className = Thread.currentThread().getStackTrace()[1].getClassName().split("\\.");
    String topologyName = className[className.length - 1];
    
    if (isLocal) {
        drpc = new LocalDRPC();
    }
    
    try {
        JStormHelper.runTopology(buildTopology(drpc), topologyName, conf, 60, new JStormHelper.CheckAckedFail(conf),
                isLocal);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Assert.fail("Failed");
    }
}
 
Example #8
Source File: TridentWordCount.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static StormTopology buildTopology(LocalDRPC drpc) {
    FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3,
            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"),
            new Values("to be or not to be the person"));
    spout.setCycle(true);
    
    TridentTopology topology = new TridentTopology();
    TridentState wordCounts = topology.newStream("spout1", spout).parallelismHint(16)
            .each(new Fields("sentence"), new Split(), new Fields("word")).groupBy(new Fields("word"))
            .persistentAggregate(new MemoryMapState.Factory(), new Count(), new Fields("count"))
            .parallelismHint(16);
            
    topology.newDRPCStream("words", drpc).each(new Fields("args"), new Split(), new Fields("word"))
            .groupBy(new Fields("word"))
            .stateQuery(wordCounts, new Fields("word"), new MapGet(), new Fields("count"))
            .each(new Fields("count"), new FilterNull())
            .aggregate(new Fields("count"), new Sum(), new Fields("sum"));
    return topology.build();
}
 
Example #9
Source File: TridentFastWordCount.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static void test() {
    TopologyBuilder builder = new TopologyBuilder();
    
    
    String[] className = Thread.currentThread().getStackTrace()[1].getClassName().split("\\.");
    String topologyName = className[className.length - 1];
    
    if (isLocal) {
        drpc = new LocalDRPC();
    }
    
    try {
        JStormHelper.runTopology(buildTopology(drpc), topologyName, conf, 60, new JStormHelper.CheckAckedFail(conf),
                isLocal);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Assert.fail("Failed");
    }
}
 
Example #10
Source File: Part05_AdvancedStateAndDRPC.java    From trident-tutorial with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    FakeTweetGenerator fakeTweets = new FakeTweetGenerator();
    FeederBatchSpout testSpout = new FeederBatchSpout(ImmutableList.of("id", "text", "actor", "location", "date"));

    Config conf = new Config();
    LocalCluster cluster = new LocalCluster();
    LocalDRPC drpc = new LocalDRPC();
    cluster.submitTopology("external_state_drpc", conf, externalState(drpc, testSpout));

    // You can use FeederBatchSpout to feed know values to the topology. Very useful for tests.
    testSpout.feed(fakeTweets.getNextTweetTuples("ted"));
    testSpout.feed(fakeTweets.getNextTweetTuples("ted"));
    testSpout.feed(fakeTweets.getNextTweetTuples("mary"));
    testSpout.feed(fakeTweets.getNextTweetTuples("jason"));

    System.out.println(drpc.execute("age_stats", ""));
    System.out.println("OK");
}
 
Example #11
Source File: TridentMinMaxOfDevicesTopology.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static void test() {
    TopologyBuilder builder = new TopologyBuilder();
    
    builder.setSpout("spout", new InOrderSpout(), 8);
    builder.setBolt("count", new Check(), 8).fieldsGrouping("spout", new Fields("c1"));
    
    conf.setMaxSpoutPending(20);
    
    String[] className = Thread.currentThread().getStackTrace()[1].getClassName().split("\\.");
    String topologyName = className[className.length - 1];
    
    if (isLocal) {
        drpc = new LocalDRPC();
    }
    
    try {
        JStormHelper.runTopology(buildDevicesTopology(), topologyName, conf, 60,
                new JStormHelper.CheckAckedFail(conf), isLocal);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Assert.fail("Failed");
    }
}
 
Example #12
Source File: ManualDRPC.java    From jstorm with Apache License 2.0 6 votes vote down vote up
public static void testDrpc() {
    TopologyBuilder builder = new TopologyBuilder();
    LocalDRPC drpc = new LocalDRPC();
    
    DRPCSpout spout = new DRPCSpout("exclamation", drpc);
    builder.setSpout("drpc", spout);
    builder.setBolt("exclaim", new ExclamationBolt(), 3).shuffleGrouping("drpc");
    builder.setBolt("return", new ReturnResults(), 3).shuffleGrouping("exclaim");
    
    LocalCluster cluster = new LocalCluster();
    Config conf = new Config();
    cluster.submitTopology("exclaim", conf, builder.createTopology());
    
    JStormUtils.sleepMs(30 * 1000);
    
    try {
        System.out.println(drpc.execute("exclamation", "aaa"));
        System.out.println(drpc.execute("exclamation", "bbb"));
    } catch (Exception e) {
        Assert.fail("Failed to test drpc");
    }
    
    drpc.shutdown();
    cluster.shutdown();
}
 
Example #13
Source File: TridentWordCount.java    From flink-perf with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
  Config conf = new Config();
  conf.setMaxSpoutPending(20);
  if (args.length == 0) {
    LocalDRPC drpc = new LocalDRPC();
    LocalCluster cluster = new LocalCluster();
    cluster.submitTopology("wordCounter", conf, buildTopology(drpc));
    for (int i = 0; i < 100; i++) {
      System.out.println("DRPC RESULT: " + drpc.execute("words", "cat the dog jumped"));
      Thread.sleep(1000);
    }
  }
  else {
    conf.setNumWorkers(3);
    StormSubmitter.submitTopologyWithProgressBar(args[0], conf, buildTopology(null));
  }
}
 
Example #14
Source File: DrpcTopology.java    From storm-example with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final LocalCluster cluster = new LocalCluster();
    final Config conf = new Config();

    LocalDRPC client = new LocalDRPC();
    TridentTopology drpcTopology = new TridentTopology();

    drpcTopology.newDRPCStream("drpc", client)
            .each(new Fields("args"), new ArgsFunction(), new Fields("gamestate"))
            .each(new Fields("gamestate"), new GenerateBoards(), new Fields("children"))
            .each(new Fields("children"), new ScoreFunction(), new Fields("board", "score", "player"))
            .groupBy(new Fields("gamestate"))
            .aggregate(new Fields("board", "score"), new FindBestMove(), new Fields("bestMove"))
            .project(new Fields("bestMove"));

    cluster.submitTopology("drpcTopology", conf, drpcTopology.build());

    Board board = new Board();
    board.board[1][1] = "O";
    board.board[2][2] = "X";
    board.board[0][1] = "O";
    board.board[0][0] = "X";
    LOG.info("Determing best move for O on:" + board.toString());
    LOG.info("RECEIVED RESPONSE [" + client.execute("drpc", board.toKey()) + "]");
}
 
Example #15
Source File: ReachTopology.java    From jstorm with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    
    LinearDRPCTopologyBuilder builder = construct();
    
    Config conf = new Config();
    conf.setNumWorkers(6);
    if (args.length != 0) {
        
        try {
            Map yamlConf = LoadConf.LoadYaml(args[0]);
            if (yamlConf != null) {
                conf.putAll(yamlConf);
            }
        } catch (Exception e) {
            System.out.println("Input " + args[0] + " isn't one yaml ");
        }
        
        StormSubmitter.submitTopology(TOPOLOGY_NAME, conf, builder.createRemoteTopology());
    } else {
        
        conf.setMaxTaskParallelism(3);
        LocalDRPC drpc = new LocalDRPC();
        LocalCluster cluster = new LocalCluster();
        cluster.submitTopology(TOPOLOGY_NAME, conf, builder.createLocalTopology(drpc));
        
        JStormUtils.sleepMs(10000);
        
        String[] urlsToTry = new String[] { "foo.com/blog/1", "engineering.twitter.com/blog/5", "notaurl.com" };
        for (String url : urlsToTry) {
            System.out.println("Reach of " + url + ": " + drpc.execute(TOPOLOGY_NAME, url));
        }
        
        cluster.shutdown();
        drpc.shutdown();
    }
}
 
Example #16
Source File: TridentReach.java    From flink-perf with Apache License 2.0 5 votes vote down vote up
public static StormTopology buildTopology(LocalDRPC drpc) {
  TridentTopology topology = new TridentTopology();
  TridentState urlToTweeters = topology.newStaticState(new StaticSingleKeyMapState.Factory(TWEETERS_DB));
  TridentState tweetersToFollowers = topology.newStaticState(new StaticSingleKeyMapState.Factory(FOLLOWERS_DB));


  topology.newDRPCStream("reach", drpc).stateQuery(urlToTweeters, new Fields("args"), new MapGet(), new Fields(
      "tweeters")).each(new Fields("tweeters"), new ExpandList(), new Fields("tweeter")).shuffle().stateQuery(
      tweetersToFollowers, new Fields("tweeter"), new MapGet(), new Fields("followers")).each(new Fields("followers"),
      new ExpandList(), new Fields("follower")).groupBy(new Fields("follower")).aggregate(new One(), new Fields(
      "one")).aggregate(new Fields("one"), new Sum(), new Fields("reach"));
  return topology.build();
}
 
Example #17
Source File: WordCountTopology.java    From storm-cassandra-cql with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    final Config configuration = new Config();
    configuration.put(MapConfiguredCqlClientFactory.TRIDENT_CASSANDRA_CQL_HOSTS, "localhost");
    final LocalCluster cluster = new LocalCluster();
    LocalDRPC client = new LocalDRPC();

    LOG.info("Submitting topology.");
    cluster.submitTopology("cqlexample", configuration, buildWordCountAndSourceTopology(client));
    LOG.info("Topology submitted.");
    Thread.sleep(10000);
    LOG.info("DRPC Query: Word Count [cat, dog, the, man]: {}", client.execute("words", "cat dog the man"));
    cluster.shutdown();
    client.shutdown();
}
 
Example #18
Source File: WordCountTopology.java    From storm-cassandra-cql with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static StormTopology buildWordCountAndSourceTopology(LocalDRPC drpc) {
    LOG.info("Building topology.");
    TridentTopology topology = new TridentTopology();

    String source1 = "spout1";
    String source2 = "spout2";
    FixedBatchSpout spout1 = new FixedBatchSpout(new Fields("sentence", "source"), 3,
            new Values("the cow jumped over the moon", source1),
            new Values("the man went to the store and bought some candy", source1),
            new Values("four score and four years ago", source2),
            new Values("how much wood can a wood chuck chuck", source2));
    spout1.setCycle(true);

    TridentState wordCounts =
            topology.newStream("spout1", spout1)
                    .each(new Fields("sentence"), new Split(), new Fields("word"))
                    .groupBy(new Fields("word", "source"))
                    .persistentAggregate(CassandraCqlMapState.nonTransactional(new WordCountAndSourceMapper()),
                            new IntegerCount(), new Fields("count"))
                    .parallelismHint(6);

    topology.newDRPCStream("words", drpc)
            .each(new Fields("args"), new Split(), new Fields("word"))
            .groupBy(new Fields("word"))
            .stateQuery(wordCounts, new Fields("word"), new MapGet(), new Fields("count"))
            .each(new Fields("count"), new FilterNull())
            .aggregate(new Fields("count"), new Sum(), new Fields("sum"));

    return topology.build();
}
 
Example #19
Source File: TridentReach.java    From jstorm with Apache License 2.0 5 votes vote down vote up
public static StormTopology buildTopology(LocalDRPC drpc) {
    TridentTopology topology = new TridentTopology();
    TridentState urlToTweeters = topology.newStaticState(new StaticSingleKeyMapState.Factory(TWEETERS_DB));
    TridentState tweetersToFollowers = topology.newStaticState(new StaticSingleKeyMapState.Factory(FOLLOWERS_DB));
    
    topology.newDRPCStream("reach", drpc)
            .stateQuery(urlToTweeters, new Fields("args"), new MapGet(), new Fields("tweeters"))
            .each(new Fields("tweeters"), new ExpandList(), new Fields("tweeter")).shuffle()
            .stateQuery(tweetersToFollowers, new Fields("tweeter"), new MapGet(), new Fields("followers"))
            .each(new Fields("followers"), new ExpandList(), new Fields("follower")).groupBy(new Fields("follower"))
            .aggregate(new One(), new Fields("one")).aggregate(new Fields("one"), new Sum(), new Fields("reach"));
    return topology.build();
}
 
Example #20
Source File: BaseLocalClusterTest.java    From storm-trident-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    esSetup = new EsSetup(settings);
    esSetup.execute(createIndex(index));

    drpc = new LocalDRPC();
    StormTopology topology = buildTopology();

    cluster = new LocalCluster();
    cluster.submitTopology("elastic-storm", new Config(), topology);

    Utils.sleep(10000); // let's do some work
}
 
Example #21
Source File: JStormUnitTestDRPCValidator.java    From jstorm with Apache License 2.0 4 votes vote down vote up
/**
 * pass a localDRPC object to execute when you call executeLocalDRPC() method.
 * @param localDRPC the localDRPC
 */
public JStormUnitTestDRPCValidator(LocalDRPC localDRPC)
{
    this.localDRPC = localDRPC;
}
 
Example #22
Source File: E8_DRPCTopology.java    From StormCV with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args){
	// first some global (topology configuration)
	StormCVConfig conf = new StormCVConfig();

	conf.put(StormCVConfig.STORMCV_OPENCV_LIB, "mac64_opencv_java248.dylib");
			
	conf.setNumWorkers(5); // number of workers in the topology
	conf.put(StormCVConfig.STORMCV_FRAME_ENCODING, Frame.JPG_IMAGE); // indicates frames will be encoded as JPG throughout the topology (JPG is the default when not explicitly set)
	conf.put(Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS, true); // True if Storm should timeout messages or not.
	conf.put(Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS , 10); // The maximum amount of time given to the topology to fully process a message emitted by a spout (default = 30)
	conf.put(StormCVConfig.STORMCV_SPOUT_FAULTTOLERANT, false); // indicates if the spout must be fault tolerant; i.e. spouts do NOT! replay tuples on fail
	conf.put(StormCVConfig.STORMCV_CACHES_TIMEOUT_SEC, 30); // TTL (seconds) for all elements in all caches throughout the topology (avoids memory overload)
	conf.put(Config.NIMBUS_TASK_LAUNCH_SECS, 30);
	
	String userDir = System.getProperty("user.dir").replaceAll("\\\\", "/");
			
	List<String> prototypes = new ArrayList<String>();
	prototypes.add( "file://"+ userDir +"/resources/data" );
	
	// create a linear DRPC builder called 'match'
	LinearDRPCTopologyBuilder builder = new LinearDRPCTopologyBuilder("match");

	//add a FeatureMatchRequestOp that receives drpc requests
	builder.addBolt(new RequestBolt(new FeatureMatchRequestOp()), 1); 
	
	 // add two bolts that perform sift extraction (as used in other examples!)
	builder.addBolt(new SingleInputBolt(
		new FeatureExtractionOp("sift", FeatureDetector.SIFT, DescriptorExtractor.SIFT).outputFrame(false)
		), 1).shuffleGrouping();

	// add bolt that matches queries it gets with the prototypes it has loaded upon the prepare.
	// The prototypes are divided over the available tasks which means that each query has to be send to all tasks (use allGrouping)
	// the matcher only reports a match if at least 1 strong match has been found (can be set to 0)
	builder.addBolt(new SingleInputBolt(new PartialMatcher(prototypes, 0, 0.5f)), 2).allGrouping(); 
	
	// add a bolt that aggregates all the results it gets from the two matchers 
	builder.addBolt(new BatchBolt(new FeatureMatchResultOp(true)), 1).fieldsGrouping(new Fields(CVParticleSerializer.REQUESTID));
	
	// create local drpc server and cluster. Deploy the drpc topology on the cluster
	LocalDRPC drpc = new LocalDRPC();
	LocalCluster cluster = new LocalCluster();
	cluster.submitTopology("drpc-demo", conf, builder.createLocalTopology(drpc));
	
	// use all face images as queries (same images as loaded by the matcher!)
	File queryDir = new File(userDir +"/resources/data/");
	for(String img : queryDir.list()){
		if(!img.endsWith(".jpg")) continue; // to avoid reading non-image files
		// execute the drpc with the image as argument. Note that the execute blocks
		String matchesJson = drpc.execute("match", "file://"+userDir +"/resources/data/"+img);
		System.out.println(img+" : " + matchesJson);
	}
		
	cluster.shutdown();
	drpc.shutdown();
}
 
Example #23
Source File: TridentFastWordCount.java    From jstorm with Apache License 2.0 4 votes vote down vote up
public static StormTopology buildTopology(LocalDRPC drpc) {
    FixedBatchSpout spout = new FixedBatchSpout(new Fields("sentence"), 3,
            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"),
            new Values("to be or not to be the person"),
            new Values("marry had a little lamb whos fleese was white as snow"),
            new Values("and every where that marry went the lamb was sure to go"),
            new Values("one two three four five six seven eight nine ten"),
            new Values("this is a test of the emergency broadcast system this is only a test"),
            new Values("peter piper picked a peck of pickeled peppers"),
            new Values("JStorm is a distributed and fault-tolerant realtime computation system."),
            new Values(
                    "Inspired by Apache Storm, JStorm has been completely rewritten in Java and provides many more enhanced features."),
            new Values("JStorm has been widely used in many enterprise environments and proved robust and stable."),
            new Values("JStorm provides a distributed programming framework very similar to Hadoop MapReduce."),
            new Values(
                    "The developer only needs to compose his/her own pipe-lined computation logic by implementing the JStorm API"),
            new Values(" which is fully compatible with Apache Storm API"),
            new Values("and submit the composed Topology to a working JStorm instance."),
            new Values("Similar to Hadoop MapReduce, JStorm computes on a DAG (directed acyclic graph)."),
            new Values("Different from Hadoop MapReduce, a JStorm topology runs 24 * 7"),
            new Values("the very nature of its continuity abd 100% in-memory architecture "),
            new Values(
                    "has been proved a particularly suitable solution for streaming data and real-time computation."),
            new Values("JStorm guarantees fault-tolerance."), new Values("Whenever a worker process crashes, "),
            new Values(
                    "the scheduler embedded in the JStorm instance immediately spawns a new worker process to take the place of the failed one."),
            new Values(" The Acking framework provided by JStorm guarantees that every single piece of data will be processed at least once.") );
    spout.setCycle(true);
    
    
    int spout_Parallelism_hint = JStormUtils.parseInt(conf.get(TOPOLOGY_SPOUT_PARALLELISM_HINT), 1);
    int split_Parallelism_hint = JStormUtils.parseInt(conf.get(TOPOLOGY_SPLIT_PARALLELISM_HINT), 2);
    int count_Parallelism_hint = JStormUtils.parseInt(conf.get(TOPOLOGY_COUNT_PARALLELISM_HINT), 2);
    
    TridentTopology topology = new TridentTopology();
    TridentState wordCounts = topology.newStream("spout1", spout).parallelismHint(spout_Parallelism_hint)
            .each(new Fields("sentence"), new Split(), new Fields("word")).parallelismHint(split_Parallelism_hint).groupBy(new Fields("word"))
            .persistentAggregate(new MemoryMapState.Factory(), new Count(), new Fields("count"))
            .parallelismHint(count_Parallelism_hint);
            
    return topology.build();
}
 
Example #24
Source File: Part05_AdvancedStateAndDRPC.java    From trident-tutorial with Apache License 2.0 4 votes vote down vote up
private static StormTopology externalState(LocalDRPC drpc, FeederBatchSpout spout) {
    TridentTopology topology = new TridentTopology();

    // You can reference existing data sources as well.
    // Here we are mocking up a "database"
    StateFactory stateFactory = new StateFactory() {
        @Override
        public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) {
            MemoryMapState<Integer> name_to_age = new MemoryMapState<Integer>("name_to_age");
            // This is a bit hard to read but it's just pre-populating the state
            List<List<Object>> keys = getKeys("ted", "mary", "jason", "tom", "chuck");
            name_to_age.multiPut(keys, ImmutableList.of(32, 21, 45, 52, 18));
            return name_to_age;
        }
    };
    TridentState nameToAge =
            topology.newStaticState(stateFactory);

    // Let's setup another state that keeps track of actor's appearance counts per location
    TridentState countState =
            topology
                    .newStream("spout", spout)
                    .groupBy(new Fields("actor","location"))
                    .persistentAggregate(new MemoryMapState.Factory(), new Count(), new Fields("count"));

    // Now, let's calculate the average age of actors seen
    topology
            .newDRPCStream("age_stats", drpc)
            .stateQuery(countState, new TupleCollectionGet(), new Fields("actor", "location"))
            .stateQuery(nameToAge, new Fields("actor"), new MapGet(), new Fields("age"))
            .each(new Fields("actor","location","age"), new Print())
            .groupBy(new Fields("location"))
            .chainedAgg()
            .aggregate(new Count(), new Fields("count"))
            .aggregate(new Fields("age"), new Sum(), new Fields("sum"))
            .chainEnd()
            .each(new Fields("sum", "count"), new DivideAsDouble(), new Fields("avg"))
            .project(new Fields("location", "count", "avg"))
    ;

    return topology.build();
}
 
Example #25
Source File: Part04_BasicStateAndDRPC.java    From trident-tutorial with Apache License 2.0 4 votes vote down vote up
private static StormTopology basicStateAndDRPC(LocalDRPC drpc, FeederBatchSpout spout) throws IOException {
        TridentTopology topology = new TridentTopology();

        // persistentAggregate persists the result of aggregation into data stores,
        // which you can use from other applications.
        // You can also use it in other topologies by using the TridentState object returned.
        //
        // The state is commonly backed by a data store like memcache, cassandra etc.
        // Here we are simply using a hash map
        TridentState countState =
                topology
                        .newStream("spout", spout)
                        .groupBy(new Fields("actor"))
                        .persistentAggregate(new MemoryMapState.Factory(), new Count(), new Fields("count"));

        // There are a few ready-made state libraries that you can use
        // Below is an example to use memcached
//        List<InetSocketAddress> memcachedServerLocations = ImmutableList.of(new InetSocketAddress("some.memcached.server",12000));
//        TridentState countStateMemcached =
//                topology
//                        .newStream("spout", spout)
//                        .groupBy(new Fields("actor"))
//                        .persistentAggregate(MemcachedState.transactional(memcachedServerLocations), new Count(), new Fields("count"));



        // DRPC stands for Distributed Remote Procedure Call
        // You can issue calls using the DRPC client library
        // A DRPC call takes two Strings, function name and function arguments
        //
        // In order to call the DRPC defined below, you'd use "count_per_actor" as the function name
        // The function arguments will be available as "args"

        /*
        topology
                .newDRPCStream("ping", drpc)
                .each(new Fields("args"), new Split(" "), new Fields("reply"))
                .each(new Fields("reply"), new RegexFilter("ping"))
                .project(new Fields("reply"));

        // You can apply usual processing primitives to DRPC streams as well
        topology
                .newDRPCStream("count", drpc)
                .each(new Fields("args"), new Split(" "), new Fields("split"))
                .each(new Fields("split"), new RegexFilter("a.*"))
                .groupBy(new Fields("split"))
                .aggregate(new Count(), new Fields("count"));   */


        // More usefully, you can query the state you created earlier
        topology
                .newDRPCStream("count_per_actor", drpc)
                .stateQuery(countState, new Fields("args"), new MapGet(), new Fields("count"));


        // Here is a more complex example
        topology
                .newDRPCStream("count_per_actors", drpc)
                .each(new Fields("args"), new Split(" "), new Fields("actor"))
                .groupBy(new Fields("actor"))
                .stateQuery(countState, new Fields("actor"), new MapGet(), new Fields("individual_count"))
                .each(new Fields("individual_count"), new FilterNull())
                .aggregate(new Fields("individual_count"), new Sum(), new Fields("count"));

        // For how to call DRPC calls, go back to the main method

        return topology.build();
    }
 
Example #26
Source File: AbstractLocalSubmitTopology.java    From jea with Apache License 2.0 4 votes vote down vote up
public LocalDRPC getClient(){
	return this.client;
}
 
Example #27
Source File: AbstractLocalSubmitTopology.java    From jea with Apache License 2.0 4 votes vote down vote up
public AbstractLocalSubmitTopology(){
	super();
	client = new LocalDRPC();
}
 
Example #28
Source File: TridentReach.java    From flink-perf with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  LocalDRPC drpc = new LocalDRPC();

  Config conf = new Config();
  LocalCluster cluster = new LocalCluster();

  cluster.submitTopology("reach", conf, buildTopology(drpc));

  Thread.sleep(2000);

  System.out.println("REACH: " + drpc.execute("reach", "aaa"));
  System.out.println("REACH: " + drpc.execute("reach", "foo.com/blog/1"));
  System.out.println("REACH: " + drpc.execute("reach", "engineering.twitter.com/blog/5"));


  cluster.shutdown();
  drpc.shutdown();
}