经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库运维 » Spark » 查看文章
Spark Streaming核心概念与编程
来源:cnblogs  作者:七支刀  时间:2018/9/25 19:47:23  对本文有异议

1. 核心概念

  • StreamingContext

    1. import org.apache.spark._
    2. import org.apache.spark.streaming._
    3.  
    4. val conf = new SparkConf().setAppName(appName).setMaster(master)
    5. //Second(1) #表示处理的批次, 当前1秒处理一次
    6. val ssc = new StreamingContext(conf, Second(1))
    1. //StreamingContext构造函数-最常用的两个
    2. /**
    3.  * Create a StreamingContext using an existing SparkContext.
    4.  * @param sparkContext existing SparkContext
    5.  * @param batchDuration the time interval at which streaming data will be divided into batches
    6.  */
    7. def this(sparkContext: SparkContext, batchDuration: Duration) = {
    8.   this(sparkContext, null, batchDuration)
    9. }
    10.  
    11. /**
    12.  * Create a StreamingContext by providing the configuration necessary for a new SparkContext.
    13.  * @param conf a org.apache.spark.SparkConf object specifying Spark parameters
    14.  * @param batchDuration the time interval at which streaming data will be divided into batches
    15.  */
    16. def this(conf: SparkConf, batchDuration: Duration) = {
    17.   this(StreamingContext.createNewSparkContext(conf), null, batchDuration)
    18. }

    batch interval可以根据你的应用程序需求的延迟要求以及集群可用的资源状况来设置

    • Spark支持两种数据源

    • 创建StreamingContext可以做什么?

    • 创建了StreamingContext后需要注意什么?

    • DStream (Discretized Streams)

      Discretized Stream or DStream is the basic abstraction provided by Spark Streaming. It represents a continuous stream of data, either the input data stream received from source, or the processed data stream generated by transforming the input stream. Internally, a DStream is represented by a continuous series of RDDs, which is Spark’s abstraction of an immutable, distributed dataset (see Spark Programming Guide for more details). Each RDD in a DStream contains data from a certain interval, as shown in the following figure.
      Discretized Stream or DStream 是Spark Streaming的一个基础抽象。它代表程序化数据流(源源不断,不停止),可以从输入数据流,或者通过Data Stream转换的。换句话说,一个DStream代表的是一系列的持续不断的RDDs。RDDs是Spark的不可变的一个分布式数据集,每一个RDD是在DStream里面一个间隔包含的数据。

      Any operation applied on a DStream translates to operations on the underlying RDDs. For example, in the earlier example of converting a stream of lines to words, the flatMap operation is applied on each RDD in the lines DStream to generate the RDDs of the words DStream. This is shown in the following figure.
      对DStream操作算子,比如map/flatMap,其实底层会被翻译为对DStream中的每个RDD做相同的操作。因为一个DStream是由不同批次的RDD构成的。

    • Input DStream and Receives

      Input DStreams are DStreams representing the stream of input data received from streaming sources. In the quick example, lines was an input DStream as it represented the stream of data received from the netcat server. Every input DStream (except file stream, discussed later in this section) is associated with a Receiver (Scala doc, Java doc) object which receives the data from a source and stores it in Spark’s memory for processing.
      Input DStreams 输入数据的流是从数据源头接收过来的数据。每一个Input DStream 都要关联一个Receiver用来接收数据从数据源存到Spark的内存中。

    • StreamingContext的构造函数

    • Create StreamingContext

      1. Basic sources: file systems, and socket connections.

      2. Advanced sources: Kafka, Flume

      1. Once a context has been started, no new streaming computations can be set up or added to it.(启动一个context后,是不可以再添加计算逻辑)

      2. Once a context has been stopped, it cannot be restarted.(一但context停止,那么就不能再使用代码重新启动)

      3. Only one StreamingContext can be active in a JVM at the same time.(一个StreamingContext只能在一个JVM中存活)

      4. stop() on StreamingContext also stops the SparkContext. To stop only the StreamingContext, set the optional parameter of stop() called stopSparkContext to false.(stop()可以停止SparkContext,如果你只想停止StreamingContext,请设置参数)

      5. A SparkContext can be re-used to create multiple StreamingContexts, as long as the previous StreamingContext is stopped (without stopping the SparkContext) before the next StreamingContext is created.(一个SparkContext可以创建多个StreamingContext)

      1. Define the input sources by creating input DStreams(通过StreamingContext可以创建输入元数据)

      2. Define the streaming computations by applying transformation and output operations to DStreams(可以通过 transformation 或者 output operations 去操作DStreams)

      3. Start receiving data and processing it using streamingContext.start()(通过使用streamingContext.start()来接受处理数据)

      4. Wait for the processing to be stopped(manually or due to any error) using streamingContext.awaitTermination()(等在处理停止(自然或者发生错误)使用streamingContext.awaitTermination())

      5. The processing can be manually stopped using streamingContext.stop()(处理时可以使用streamingContext.stop()来停止)

    2. Transformations

    Similar to that of RDDs, transformations allow the data from the input DStream to be modified. DStreams support many of the transformations available on normal Spark RDD’s. Some of the common ones are as follows.
    和RDD操作很相似,可以从input DStream 转换成一个新的。函数和RDD操作差不多!

    TransformationMeaning
    map(func)Return a new DStream by passing each element of the source DStream through a function func.
    flatMap(func)Similar to map, but each input item can be mapped to 0 or more output items.
    filter(func)Return a new DStream by selecting only the records of the source DStream on which func returns true.
    repartition(numPartitions)Changes the level of parallelism in this DStream by creating more or fewer partitions.
    union(otherStream)Return a new DStream that contains the union of the elements in the source DStream and otherDStream.
    count()Return a new DStream of single-element RDDs by counting the number of elements in each RDD of the source DStream.
    reduce(func)Return a new DStream of single-element RDDs by aggregating the elements in each RDD of the source DStream using a function func (which takes two arguments and returns one). The function should be associative and commutative so that it can be computed in parallel.
    countByValue()When called on a DStream of elements of type K, return a new DStream of (K, Long) pairs where the value of each key is its frequency in each RDD of the source DStream.
    reduceByKey(func, [numTasks])When called on a DStream of (K, V) pairs, return a new DStream of (K, V) pairs where the values for each key are aggregated using the given reduce function. Note: By default, this uses Spark's default number of parallel tasks (2 for local mode, and in cluster mode the number is determined by the config property spark.default.parallelism) to do the grouping. You can pass an optional numTasks argument to set a different number of tasks.
    join(otherStream, [numTasks])When called on two DStreams of (K, V) and (K, W) pairs, return a new DStream of (K, (V, W)) pairs with all pairs of elements for each key.
    cogroup(otherStream, [numTasks])When called on a DStream of (K, V) and (K, W) pairs, return a new DStream of (K, Seq[V], Seq[W]) tuples.
    transform(func)Return a new DStream by applying a RDD-to-RDD function to every RDD of the source DStream. This can be used to do arbitrary RDD operations on the DStream.
    updateStateByKey(func)Return a new "state" DStream where the state for each key is updated by applying the given function on the previous state of the key and the new values for the key. This can be used to maintain arbitrary state data for each key.

    3. Output Operations

    Output operations allow DStream’s data to be pushed out to external systems like a database or a file systems. Since the output operations actually allow the transformed data to be consumed by external systems, they trigger the actual execution of all the DStream transformations (similar to actions for RDDs). Currently, the following output operations are defined:
    Output operations可以把数据写到外部的数据源(database, file system)

    Output OperationMeaning
    print()Prints the first ten elements of every batch of data in a DStream on the driver node running the streaming application. This is useful for development and debugging. Python API This is called pprint() in the Python API.
    saveAsTextFiles(prefix, [suffix])Save this DStream's contents as text files. The file name at each batch interval is generated based on prefix and suffix: "prefix-TIME_IN_MS[.suffix]".
    saveAsObjectFiles(prefix, [suffix])Save this DStream's contents as SequenceFiles of serialized Java objects. The file name at each batch interval is generated based on prefix and suffix: "prefix-TIME_IN_MS[.suffix]". Python API This is not available in the Python API.
    saveAsHadoopFiles(prefix, [suffix])Save this DStream's contents as Hadoop files. The file name at each batch interval is generated based on prefix and suffix: "prefix-TIME_IN_MS[.suffix]". Python API This is not available in the Python API.
    foreachRDD(func)The most generic output operator that applies a function, func, to each RDD generated from the stream. This function should push the data in each RDD to an external system, such as saving the RDD to files, or writing it over the network to a database. Note that the function func is executed in the driver process running the streaming application, and will usually have RDD actions in it that will force the computation of the streaming RDDs.

    4. 实战案例

    • 基础 Maven pom.xml 依赖配置

    1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    2.         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    3.   <groupId>org.ko</groupId>
    4.   <version>1.0.0-SNAPSHOT</version>
    5.   <modelVersion>4.0.0</modelVersion>
    6.   <artifactId>spark-streaming</artifactId>
    7.   <inceptionYear>2008</inceptionYear>
    8.   <properties>
    9.       <scala.version>2.11.12</scala.version>
    10.       <kafka.version>2.0.0</kafka.version>
    11.       <spark.version>2.2.1</spark.version>
    12.       <hadoop.version>3.1.0</hadoop.version>
    13.       <hbase.version>2.1.0</hbase.version>
    14.       <jackson.version>2.9.2</jackson.version>
    15.   </properties>
    16.  
    17.   <dependencies>
    18.       <!--Hadoop 依赖-->
    19.       <dependency>
    20.           <groupId>org.apache.hadoop</groupId>
    21.           <artifactId>hadoop-client</artifactId>
    22.           <version>${hadoop.version}</version>
    23.       </dependency>
    24.  
    25.       <!--Spark Streaming 依赖-->
    26.       <dependency>
    27.           <groupId>org.apache.spark</groupId>
    28.           <artifactId>spark-streaming_2.11</artifactId>
    29.           <version>${spark.version}</version>
    30.       </dependency>
    31.  
    32.       <!--HBase Client 依赖-->
    33.       <dependency>
    34.           <groupId>org.apache.hbase</groupId>
    35.           <artifactId>hbase-client</artifactId>
    36.           <version>${hbase.version}</version>
    37.       </dependency>
    38.  
    39.       <!--Jackson json处理工具包-->
    40.       <dependency>
    41.           <groupId>com.fasterxml.jackson.module</groupId>
    42.           <artifactId>jackson-module-scala_2.11</artifactId>
    43.           <version>${jackson.version}</version>
    44.       </dependency>
    45.  
    46.       <!--HBase Server 依赖-->
    47.       <!--<dependency>
    48.           <groupId>org.apache.hbase</groupId>
    49.           <artifactId>hbase-server</artifactId>
    50.           <version>${hbase.version}</version>
    51.       </dependency>-->
    52.  
    53.       <!--Scala Library-->
    54.       <dependency>
    55.           <groupId>org.scala-lang</groupId>
    56.           <artifactId>scala-library</artifactId>
    57.           <version>${scala.version}</version>
    58.       </dependency>
    59.  
    60.       <!--Kafka 依赖-->
    61.       <dependency>
    62.           <groupId>org.apache.kafka</groupId>
    63.           <artifactId>kafka_2.11</artifactId>
    64.           <version>${kafka.version}</version>
    65.           <exclusions>
    66.               <exclusion>
    67.                   <groupId>org.xerial.snappy</groupId>
    68.                   <artifactId>snappy-java</artifactId>
    69.               </exclusion>
    70.               <exclusion>
    71.                   <groupId>com.fasterxml.jackson.core</groupId>
    72.                   <artifactId>*</artifactId>
    73.               </exclusion>
    74.           </exclusions>
    75.       </dependency>
    76.       <dependency>
    77.           <groupId>org.xerial.snappy</groupId>
    78.           <artifactId>snappy-java</artifactId>
    79.           <version>1.1.2.6</version>
    80.       </dependency>
    81.   </dependencies>
    82.  
    83.   <!--cdh hadoop repository-->
    84.   <!--<repositories>
    85.       <repository>
    86.           <id>cloudera</id>
    87.           <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
    88.       </repository>
    89.   </repositories>-->
    90.  
    91.   <build>
    92.       <sourceDirectory>src/main/scala</sourceDirectory>
    93.       <testSourceDirectory>src/test/scala</testSourceDirectory>
    94.       <plugins>
    95.           <plugin>
    96.               <groupId>org.scala-tools</groupId>
    97.               <artifactId>maven-scala-plugin</artifactId>
    98.               <version>2.15.1</version>
    99.               <executions>
    100.                   <execution>
    101.                       <goals>
    102.                           <goal>compile</goal>
    103.                           <goal>testCompile</goal>
    104.                       </goals>
    105.                   </execution>
    106.               </executions>
    107.               <configuration>
    108.                   <scalaVersion>${scala.version}</scalaVersion>
    109.                   <args>
    110.                       <arg>-target:jvm-1.5</arg>
    111.                   </args>
    112.               </configuration>
    113.           </plugin>
    114.           <plugin>
    115.               <groupId>org.apache.maven.plugins</groupId>
    116.               <artifactId>maven-eclipse-plugin</artifactId>
    117.               <configuration>
    118.                   <downloadSources>true</downloadSources>
    119.                   <buildcommands>
    120.                       <buildcommand>ch.epfl.lamp.sdt.core.scalabuilder</buildcommand>
    121.                   </buildcommands>
    122.                   <additionalProjectnatures>
    123.                       <projectnature>ch.epfl.lamp.sdt.core.scalanature</projectnature>
    124.                   </additionalProjectnatures>
    125.                   <classpathContainers>
    126.                       <classpathContainer>org.eclipse.jdt.launching.JRE_CONTAINER</classpathContainer>
    127.                       <classpathContainer>ch.epfl.lamp.sdt.launching.SCALA_CONTAINER</classpathContainer>
    128.                   </classpathContainers>
    129.               </configuration>
    130.           </plugin>
    131.           <plugin>
    132.               <groupId>org.apache.maven.plugins</groupId>
    133.               <artifactId>maven-compiler-plugin</artifactId>
    134.               <configuration>
    135.                   <source>8</source>
    136.                   <target>8</target>
    137.               </configuration>
    138.           </plugin>
    139.       </plugins>
    140.   </build>
    141.   <reporting>
    142.       <plugins>
    143.           <plugin>
    144.               <groupId>org.scala-tools</groupId>
    145.               <artifactId>maven-scala-plugin</artifactId>
    146.               <configuration>
    147.                   <scalaVersion>${scala.version}</scalaVersion>
    148.               </configuration>
    149.           </plugin>
    150.       </plugins>
    151.   </reporting>
    152. </project>
    • Spark Streaming处理socket数据

      1. /**
      2.   * Spark Streaming 处理socket数据
      3.   *
      4.   * 测试: nc -lk 6789
      5.   */
      6. object NetworkWordCount {
      7.  
      8.   def main(args: Array[String]): Unit = {
      9.     //1. 创建spark conf配置
      10.     val sparkConf = new SparkConf()
      11.       .setMaster("local[2]")
      12.       .setAppName("NetworkWordCount")
      13.  
      14.     //2. 创建StreamingContext需要两个参数: SparkConf 和 batch interval
      15.     val ssc = new StreamingContext(sparkConf, Seconds(5))
      16.     val lines = ssc.socketTextStream("192.168.37.128", 6789)
      17.  
      18.     val result = lines.flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_)
      19.  
      20.     result.print()
      21.  
      22.     ssc.start()
      23.     ssc.awaitTermination()
      24.   }
      25. }

      ReceiverSpark Core 处理都需要系统资源,所有2个是最低的数量。

      • 2.为什么local[?], 一定要设置为2

      • 1.代码实现

    • Spark Streaming 处理 HDFS 文件数据

      1. /**
      2.   * <p>
      3.   *   使用Spark Streaming 处理文件系统(local/HDFS)的数据
      4.   * </p>
      5.   */
      6. object FileWordCount {
      7.  
      8.   def main(args: Array[String]): Unit = {
      9.     val sparkConf = new SparkConf()
      10.       .setMaster("local")
      11.       .setAppName("FileWordCount")
      12.  
      13.     val ssc = new StreamingContext(sparkConf, Seconds(5))
      14.  
      15.     val lines = ssc.textFileStream("D:\\tmp")
      16.  
      17.     val result = lines.flatMap(_.split(" ")).map((_, 1)).reduceByKey(_+_)
      18.  
      19.     result.print()
      20.  
      21.     ssc.start()
      22.     ssc.awaitTermination()
      23.   }
      24.  
      25. }

      Spark Streaming会持续监控数据文件夹变化,现在不支持递归嵌套文件夹。

      • The files must have the same data format.(文件格式必须一样)

      • The files must be create in the dataDirectory by atomically moving or renaming them into the data directory.(这个文件必须创建在数据文件夹,并且是原子性的移动或者改变名字到监控文件夹)

      • Once moved, the files must not be changed. So if the files are being continuously appended, the new data will not be read.(一但移动就不可以再改变,是持久的被添加进去,新写入数据不会被处理。)

      • 注意事项

      • 代码实现

       友情链接:直通硅谷  点职佳  北美留学生论坛

      本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

      W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
      关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
      皖ICP备17017327号-2 皖公网安备34020702000426号