Spark笔记-sparkStreaming代码演示

Hdfs文件演示
///
///      代码        //
///
package week5


import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.StreamingContext._




object HdfsWordCount {
  def main(args: Array[String]) {
    val sparkConf = new SparkConf().setAppName("HdfsWordCount").setMaster("local[2]")
    // Create the context
    val ssc = new StreamingContext(sparkConf, Seconds(20))


    val lines = ssc.textFileStream("/home/mmicky/temp/")
    val words = lines.flatMap(_.split(" "))
    val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _)
    wordCounts.print()
    ssc.start()
    ssc.awaitTermination()
  }
}


*************************************************************************
*************************************************************************
*************************************************************************
销售模拟器:参数1:读入的文件;参数2:端口;参数3:发送时间间隔ms
打包的时候注意,可以将应用的jar包打进去;
也可以修改classpath,注意每个jar包用空格隔开,如:
/home/spark/modules/scala-2.10.5/lib/scala-swing.jar /home/spark/modules/scala-2.10.5/lib/scala-library.jar /home/spark/modules/scala-2.10.5/lib/scala-actors.jar
测试:
java -cp week5.jar week5.SaleSimulation /home/mmicky/data/spark/people.txt 9999 1000




///
///      代码        //
///
package week5


import java.io.{PrintWriter}
import java.net.ServerSocket
import scala.io.Source


object SaleSimulation {
  def index(length: Int) = {
    import java.util.Random
    val rdm = new Random


    rdm.nextInt(length)
  }


  def main(args: Array[String]) {
    if (args.length != 3) {
      System.err.println("Usage: <filename> <port> <millisecond>")
      System.exit(1)
    }


//args(0)读入的文件
    val filename = args(0)
    val lines = Source.fromFile(filename).getLines.toList
    val filerow = lines.length


//args(1)端口
    val listener = new ServerSocket(args(1).toInt)
    while (true) {
      val socket = listener.accept()
      new Thread() {
        override def run = {
          println("Got client connected from: " + socket.getInetAddress)
          val out = new PrintWriter(socket.getOutputStream(), true)
          while (true) {
 //args(2)发送时间间隔ms
            Thread.sleep(args(2).toLong)
            val content = lines(index(filerow))
            println(content)
            out.write(content + '\n')
            out.flush()
          }
          socket.close()
        }
      }.start()
    }
  }
}


*************************************************************************
*************************************************************************
*************************************************************************


网络数据演示
///
///      代码        //
///
package week5


import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.streaming.{Milliseconds, Seconds, StreamingContext}
import org.apache.spark.streaming.StreamingContext._
import org.apache.spark.storage.StorageLevel


object NetworkWordCount {
  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("NetworkWordCount").setMaster("local[2]")
    val sc = new SparkContext(conf)
    val ssc = new StreamingContext(sc, Seconds(5))


    val lines = ssc.socketTextStream(args(0), args(1).toInt, StorageLevel.MEMORY_AND_DISK_SER)
    val words = lines.flatMap(_.split(","))
    val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _)


    wordCounts.print()
    ssc.start()
    ssc.awaitTermination()
  }
}




*************************************************************************
*************************************************************************
*************************************************************************


stateful演示
///
///      代码        //
///
package week5


import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.StreamingContext._


object StatefulWordCount {
  def main(args: Array[String]) {


    val updateFunc = (values: Seq[Int], state: Option[Int]) => {
      val currentCount = values.foldLeft(0)(_ + _)
      val previousCount = state.getOrElse(0)
      Some(currentCount + previousCount)
    }


    val conf = new SparkConf().setAppName("StatefulWordCount").setMaster("local[2]")
    val sc = new SparkContext(conf)


    //创建StreamingContext
    val ssc = new StreamingContext(sc, Seconds(5))
    ssc.checkpoint(".")


    //获取数据
    val lines = ssc.socketTextStream(args(0), args(1).toInt)
    val words = lines.flatMap(_.split(","))
    val wordCounts = words.map(x => (x, 1))


    //使用updateStateByKey来更新状态
    val stateDstream = wordCounts.updateStateByKey[Int](updateFunc)
    stateDstream.print()
    ssc.start()
    ssc.awaitTermination()
  }
}






*************************************************************************
*************************************************************************
*************************************************************************


window演示
///
///      代码        //
///
package week5


import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming._
import org.apache.spark.streaming.StreamingContext._


object WindowWordCount {
  def main(args: Array[String]) {


    val conf = new SparkConf().setAppName("WindowWordCount").setMaster("local[2]")
    val sc = new SparkContext(conf)


    //创建StreamingContext
    val ssc = new StreamingContext(sc, Seconds(5))
    ssc.checkpoint(".")


    // //获取数据
    val lines = ssc.socketTextStream(args(0), args(1).toInt, StorageLevel.MEMORY_ONLY_SER)
    val words = lines.flatMap(_.split(","))


    //windows操作
    val wordCounts = words.map(x => (x , 1)).reduceByKeyAndWindow((a:Int,b:Int) => (a + b), Seconds(args(2).toInt), Seconds(args(3).toInt))
    //val wordCounts = words.map(x => (x , 1)).reduceByKeyAndWindow(_+_, _-_,Seconds(args(2).toInt), Seconds(args(3).toInt))


    wordCounts.print()
    ssc.start()
    ssc.awaitTermination()
  }
}




*************************************************************************
*************************************************************************
*************************************************************************


sale数据演示
//qryStockDetail.txt文件定义了订单明细
//订单号,行号,货品,数量,单价,金额
使用方法:
java -cp week5.jar week5.SaleSimulation /home/mmicky/data/spark/saledata/qryStockDetail.txt 9999 100
///
///      代码        //
///
package week5


import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.streaming.{Milliseconds, Seconds, StreamingContext}
import org.apache.spark.streaming.StreamingContext._
import org.apache.spark.storage.StorageLevel


object SaleAmount {
  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("SaleAmount").setMaster("local[2]")
    val sc = new SparkContext(conf)
    val ssc = new StreamingContext(sc, Seconds(5))


    val lines = ssc.socketTextStream(args(0), args(1).toInt, StorageLevel.MEMORY_AND_DISK_SER)
    val words = lines.map(_.split(",")).filter(_.length == 6)
    val wordCounts = words.map(x=>(1, x(5).toDouble)).reduceByKey(_ + _)


    wordCounts.print()
    ssc.start()
    ssc.awaitTermination()
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spark Streaming是Apache Spark的一个组件,它提供了实时数据处理的能力。它可以从各种数据源(如Kafka、Flume、Twitter、HDFS等)中读取数据,并将其转换为离散的批次进行处理。Spark Streaming使用类似于Spark的API,可以使用Scala、Java和Python编写应用程序。它还提供了一些高级功能,如窗口操作和状态管理,使得处理实时数据变得更加容易和高效。 ### 回答2: Spark是由Apache提供的一种基于内存计算的大数据处理框架。它支持多种数据处理场景,包括批处理、交互式查询、机器学习和流处理等。其中,Spark StreamingSpark提供的一种流处理模块,它能够将实时数据流处理成离散的小批次数据,然后交给Spark进行处理。 Spark Streaming的核心思想是将实时数据流划分成一系列的小批次数据,然后按照某种规则进行处理。这种处理方式可以使得Spark Streaming能够适应高并发、高吞吐量和低延迟的数据流处理场景。具体来说,Spark Streaming提供了以下几个重要的特性: 1.高吞吐量:Spark Streaming使用高效的内存计算技术,能够快速处理大规模数据,同时保证较高的吞吐量。 2.低延迟:Spark Streaming采用小批次处理的方式,能够将延迟降低到毫秒级别,满足实时数据流的处理需求。 3.易于使用:Spark Streaming提供了高级API和与Spark Batch API类似的编程模型,使得开发人员可以很快上手。 4.高可靠性:Spark Streaming提供了容错机制,能够自动恢复失败的任务,提高了系统的稳定性。 总之,Spark Streaming是一种性能高、延迟低、易用性好的流处理框架,适用于实时数据分析、监控和处理场景等。在大数据时代,Spark Streaming必将成为数据科学和工程领域的核心工具之一。 ### 回答3: Spark是开源的大数据处理框架,它提供了一个基于内存的分布式计算引擎,用于处理大规模数据集。Spark StreamingSpark的一个组件,它提供了实时数据处理的能力。 Spark Streaming通过将数据流拆分成一系列微小的批次,采用与Spark批处理类似的技术来处理实时数据。这样,Spark Streaming可以将实时数据转化为RDD(弹性分布式数据集),并使用Spark上可用的所有算子来处理它们。在Spark Streaming中,数据批次被不断收集并进入一个数据结构中,称为DStream(持续型的流式数据集)。DStream是由一系列RDD构成的,这些RDD代表了数据流中的每个微小批次。 Spark Streaming可以从多种数据源接收数据,如Kafka、Flume等,还可以与HDFS、HBase等大数据存储系统进行集成。它还支持复杂的流式处理操作,如窗口、状态更新和迭代处理等。 总之,Spark Streaming为实时数据处理提供了一种非常强大和灵活的解决方案,可以帮助企业快速地处理实时数据和提高决策能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值