1.代码:
val conf = new SparkConf();
conf.setAppName("OnlineHottestItems");
conf.setMaster("spark://Master:7077");
/**
* 此处设置Batch Interval是在Spark Streaming中生成基本job的时间单位,窗口和滑动时间间隔
* 一定是改Batch Interval的整数倍
*/
val ssc = new StreamingContext(conf, Seconds(5));
ssc.checkpoint("/library/onlinehot/")
val hottestStream = ssc.socketTextStream("Master", 9999)
/**
* 用户搜索的格式简化为name item,在这里我们由于要计算出热点内容,所以只需要提取item即可
* 提取出的item然后通过map转换为(item,1)
*/
val searchPair = hottestStream.map(_.split(" ")(1)).map(item => (item, 1))
//val hottestDStream = searchPair.reduceByKeyAndWindow((v1: Int, v2: Int) => v1 + v2, Seconds(60), Seconds(20))
val hottestDStream = searchPair.reduceByKeyAndWindow((v1: Int, v2: Int) => v1 + v2, (v1: Int, v2: Int) => v1 - v2, Seconds(60), Seconds(20))
//如果操作没有排序,可以通过transform扩展
hottestDStream.transform(hottestItemRDD => {
val top3 = hottestItemRDD.map(pair => (pair._2, pair._1)).sortByKey(false).
map(pair => (pair._2, pair._1)).
take(3) //选出前3个
for (item <- top3) {
println(item)
}
hottestItemRDD
/**
* 计算后的有效数据一般都会写入kafka中,下游的计费系统会从kafka中pull到有效数据进行计费
*/