spark streaming 示例

1、监控本地文件夹下的文件信息

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import org.apache.spark.SparkConf  
  2. import org.apache.spark.streaming.{Seconds, StreamingContext}  
  3. import org.apache.spark.streaming.StreamingContext._  
  4.   
  5.   
  6. object HdfsWordCount {  
  7.   def main(args: Array[String]) {  
  8.     val sparkConf = new SparkConf().setAppName("HdfsWordCount").setMaster("local[2]")//这里指在本地运行,2个线程,一个监听,一个处理数据  
  9.     // Create the context  
  10.     val ssc = new StreamingContext(sparkConf, Seconds(20))// 时间划分为20秒  
  11.   
  12.     val lines = ssc.textFileStream("/home/mmicky/temp/")  
  13.     val words = lines.flatMap(_.split(" "))  
  14.     val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _)  
  15.     wordCounts.print()  
  16.     ssc.start()  
  17.     ssc.awaitTermination()  
  18.   }  
  19. }  
2、 网络socket监控

1)构建socket模拟周期发送数据

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import java.io.{PrintWriter}  
  2. import java.net.ServerSocket  
  3. import scala.io.Source  
  4.   
  5. object SaleSimulation {  
  6.   def index(length: Int) = { //销售模拟器:参数1:读入的文件;参数2:端口;参数3:发送时间间隔ms  
  7.     import java.util.Random  
  8.     val rdm = new Random  
  9.   
  10.     rdm.nextInt(length)  
  11.   }  
  12.   
  13.   def main(args: Array[String]) {  
  14.     if (args.length != 3) {  
  15.       System.err.println("Usage: <filename> <port> <millisecond>")  
  16.       System.exit(1)  
  17.     }  
  18.   
  19.     val filename = args(0)  
  20.     val lines = Source.fromFile(filename).getLines.toList  
  21.     val filerow = lines.length  
  22.   
  23.     val listener = new ServerSocket(args(1).toInt)  
  24.     while (true) {  
  25.       val socket = listener.accept()  
  26.       new Thread() {  
  27.         override def run = {  
  28.           println("Got client connected from: " + socket.getInetAddress)  
  29.           val out = new PrintWriter(socket.getOutputStream(), true)  
  30.           while (true) {  
  31.             Thread.sleep(args(2).toLong)  
  32.             val content = lines(index(filerow))  
  33.             println(content)  
  34.             out.write(content + '\n')  
  35.             out.flush()  
  36.           }  
  37.           socket.close()  
  38.         }  
  39.       }.start()  
  40.     }  
  41.   }  
  42. }  
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. 运行:java -cp week5.jar week5.SaleSimulation /home/mmicky/data/spark/people.txt 9999 1000 //从people文件随机读取,发送端口9999,间隔1秒  
2)sparkStream 监控端

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import org.apache.spark.{SparkContext, SparkConf}  
  2. import org.apache.spark.streaming.{Milliseconds, Seconds, StreamingContext}  
  3. import org.apache.spark.streaming.StreamingContext._  
  4. import org.apache.spark.storage.StorageLevel  
  5.   
  6. object NetworkWordCount {  
  7.   def main(args: Array[String]) {  
  8.     val conf = new SparkConf().setAppName("NetworkWordCount").setMaster("local[2]")  
  9.     val sc = new SparkContext(conf)  
  10.     val ssc = new StreamingContext(sc, Seconds(5))//5秒间隔  
  11.    
  12.     val lines = ssc.socketTextStream(args(0), args(1).toInt, StorageLevel.MEMORY_AND_DISK_SER)// 服务器地址,端口,序列化方案  
  13.     val words = lines.flatMap(_.split(","))  
  14.     val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _)  
  15.   
  16.     wordCounts.print()  
  17.     ssc.start()  
  18.     ssc.awaitTermination()  
  19.   }  
  20. }  
3、监控有状态(stateful)
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import org.apache.spark.{SparkContext, SparkConf}  
  2. import org.apache.spark.streaming.{Seconds, StreamingContext}  
  3. import org.apache.spark.streaming.StreamingContext._  
  4.   
  5. object StatefulWordCount {  
  6.   def main(args: Array[String]) {  
  7.   
  8.     val updateFunc = (values: Seq[Int], state: Option[Int]) => { //StateFul需要定义的处理函数,第一个参数是本次进来的值,第二个是过去处理后保存的值  
  9.       val currentCount = values.foldLeft(0)(_ + _)//求和  
  10.       val previousCount = state.getOrElse(0)// 如果过去没有 即取0  
  11.       Some(currentCount + previousCount)// 求和  
  12.     }  
  13.   
  14.     val conf = new SparkConf().setAppName("StatefulWordCount").setMaster("local[2]")  
  15.     val sc = new SparkContext(conf)  
  16.   
  17.     //创建StreamingContext  
  18.     val ssc = new StreamingContext(sc, Seconds(5))  
  19.     ssc.checkpoint(".")//因为是有状态的,需要保存之前的信息,所以这里设定了 checkpoint的目录,以防断电后内存数据丢失。  
  20. //这里因为没有设置checkpoint的时间间隔,所以会发现每一次数据块过来 即切分一次,产生一个 .checkpoint 文件  
  21.     //获取数据  
  22.     val lines = ssc.socketTextStream(args(0), args(1).toInt)  
  23.     val words = lines.flatMap(_.split(","))  
  24.     val wordCounts = words.map(x => (x, 1))  
  25.   
  26.     //使用updateStateByKey来更新状态  
  27.     val stateDstream = wordCounts.updateStateByKey[Int](updateFunc)//调用处理函数 updateFunc  
  28.     stateDstream.print()  
  29.     ssc.start()  
  30.     ssc.awaitTermination()  
  31.   }  
  32. }  
4、windows操作

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import org.apache.spark.{SparkContext, SparkConf}  
  2. import org.apache.spark.storage.StorageLevel  
  3. import org.apache.spark.streaming._  
  4. import org.apache.spark.streaming.StreamingContext._  
  5.   
  6. object WindowWordCount {  
  7.   def main(args: Array[String]) {  
  8.   
  9.     val conf = new SparkConf().setAppName("WindowWordCount").setMaster("local[2]")  
  10.     val sc = new SparkContext(conf)  
  11.   
  12.     //创建StreamingContext  
  13.     val ssc = new StreamingContext(sc, Seconds(5))  
  14.     ssc.checkpoint(".")  
  15.   
  16.     // //获取数据  
  17.     val lines = ssc.socketTextStream(args(0), args(1).toInt, StorageLevel.MEMORY_ONLY_SER)  
  18.     val words = lines.flatMap(_.split(","))  
  19.   
  20.     //windows操作  
  21.     val wordCounts = words.map(x => (x , 1)).reduceByKeyAndWindow((a:Int,b:Int) => (a + b), Seconds(args(2).toInt), Seconds(args(3).toInt))
  22. //第二个参数是 windows的窗口时间间隔,比如是 监听间隔的 倍数,上面是 5秒,这里必须是5的倍数。eg :30  
  23. //第三个参数是 windows的滑动时间间隔,也必须是监听间隔的倍数。eg :10  
  24. //那么这里的作用是, 每隔10秒钟,对前30秒的数据, 进行一次处理,这里的处理就是 word count。  
  25.     //val wordCounts = words.map(x => (x , 1)).reduceByKeyAndWindow(_+_, _-_,Seconds(args(2).toInt), Seconds(args(3).toInt))  
  26. //这个是优化方法, 即加上上一次的结果,减去 上一次存在又不在这一次的数据块的部分。  
  27.     //val sortedWordCount = wordCounts.map{case(char, count) => (count, char)}.transform{_.sortByKey(false)}.map{case(char, count) => (count, char)}
  28.     //这个地方用transform,而不直接使用sortByKey,是因为sortByKey只能对单个RDD进行操作,而wordCounts是一连串的RDD,所以这里需要用transform来对这一连串的RDD进行sortByKey操作。
  29.     wordCounts.print()  
  30.     //sortedWordCount.print()
  31.     ssc.start()  
  32.     ssc.awaitTermination()  
  33.   }  
  34. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值