reduceByKeyAndWindow

2020-04-05 323次浏览 已收录 8个评论

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

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

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();
 }
}

 


渣渣龙, 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:reduceByKeyAndWindow
喜欢 (1)

您必须 登录 才能发表评论!

(8)个小伙伴在吐槽
  1. 记住这个网站了
    小白2020-04-06 09:57
  2. good厉害了
    渣渣混2020-04-06 09:57
  3. 以后多发点哦
    努力2020-04-06 09:59
  4. 记住这个网站了
    靓妹2020-04-06 09:59
  5. good厉害了
    渣渣辉2020-04-06 10:00
  6. 还可以
    渣渣混2020-04-06 10:02
  7. 以后多多交流
    你哥2020-05-26 09:32
  8. good厉害了
    奋斗2020-05-26 09:57