reduceByKeyAndWindow

首页 » Spark » reduceByKeyAndWindow

我以每隔5秒计算这15秒内的3个批次的数据,也就是窗口长度是15,滑动间隔是5s。

reduceByKeyAndWindow

我使用的是优化后的窗口函数,会在滑动间隔后用checkpoint保存key的状态0。

reduceByKeyAndWindow
package spark;

import java.util.Arrays;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;

import scala.Tuple2;

public class windowoperator {
 public static void main(String[] args) {
  SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("window");
  JavaStreamingContext jssc=new JavaStreamingContext(conf,Durations.seconds(5));
  //不输出日志
  jssc.sparkContext().setLogLevel("WARN");
  jssc.checkpoint("./checkpoint");//必须有
  JavaReceiverInputDStream<String>searchLogsDStream = jssc.socketTextStream("192.168.2.14", 9999);
  JavaDStream<String> searchWordsDStream = searchLogsDStream.flatMap(new FlatMapFunction<String, String>() {

   @Override
   public Iterable<String> call(String line) throws Exception {
    // TODO Auto-generated method stub
    return Arrays.asList(line.split(" "));
   }
  });
  JavaPairDStream<String, Integer> searchWordPairDStream = searchWordsDStream.mapToPair(new PairFunction<String, String, Integer>() {

   @Override
   public Tuple2<String, Integer> call(String word) throws Exception {
    // TODO Auto-generated method stub
    return new Tuple2<String, Integer>(word,1);
   }
  });
  JavaPairDStream<String,Integer> searchWordCountsDStream = 
    searchWordPairDStream.reduceByKeyAndWindow(new Function2<Integer, Integer, Integer>() {
   
   @Override
   public Integer call(Integer v1, Integer v2) throws Exception {
    // TODO Auto-generated method stub
    return v1+v2;//加的是进来的那几个批次的数据
   }
  }, new Function2<Integer, Integer, Integer>() {

   @Override
   public Integer call(Integer v1, Integer v2) throws Exception {
    // TODO Auto-generated method stub
    return v1-v2;//减的是出去的那几个批次的数据
   }
  },Durations.seconds(15),Durations.seconds(5));
  //每隔5秒计算这15秒内的3个批次的数据
  //窗口长度;滑动间隔
  searchWordCountsDStream.print();
  jssc.start();
  jssc.awaitTermination();
 }
}

 

分享到:
赞(0) 打赏

评论 8

评论前必须登录!

 

  1. #1

    记住这个网站了

    小白8个月前 (04-06)
  2. #2

    good厉害了

    渣渣混8个月前 (04-06)
  3. #3

    以后多发点哦

    努力8个月前 (04-06)
  4. #4

    记住这个网站了

    靓妹8个月前 (04-06)
  5. #5

    good厉害了

    渣渣辉8个月前 (04-06)
  6. #6

    还可以

    渣渣混8个月前 (04-06)
  7. #7

    以后多多交流

    你哥6个月前 (05-26)
  8. #8

    good厉害了

    奋斗6个月前 (05-26)

觉得文章有用就打赏一下弟弟吧

支付宝扫一扫打赏

微信扫一扫打赏

Vieu4.5主题
专业打造轻量级个人企业风格博客主题!专注于前端开发,全站响应式布局自适应模板。
正在播放:

作者想对您说:

累了就停下来听首歌吧

听完后会给您一个好心情

最后

等到您不容易

还希望您能多待一会儿

      00:00/00:00