欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spark Streaming核心概念与编程

程序员文章站 2022-07-05 14:12:58
1. 核心概念 StreamingContext Create StreamingContext StreamingContext的构造函数 batch interval 可以根据你的应用程序需求的延迟要求以及集群可用的资源状况来设置 创建StreamingContext可以做什么? 1. Defi ......

1. 核心概念

  • streamingcontext
    • create streamingcontext
    import org.apache.spark._
    import org.apache.spark.streaming._
    
    val conf = new sparkconf().setappname(appname).setmaster(master)
    //second(1) #表示处理的批次, 当前1秒处理一次
    val ssc = new streamingcontext(conf, second(1))
    • streamingcontext的构造函数
    //streamingcontext构造函数-最常用的两个
    /**
     * create a streamingcontext using an existing sparkcontext.
     * @param sparkcontext existing sparkcontext
     * @param batchduration the time interval at which streaming data will be divided into batches
     */
    def this(sparkcontext: sparkcontext, batchduration: duration) = {
      this(sparkcontext, null, batchduration)
    }
    
    /**
     * create a streamingcontext by providing the configuration necessary for a new sparkcontext.
     * @param conf a org.apache.spark.sparkconf object specifying spark parameters
     * @param batchduration the time interval at which streaming data will be divided into batches
     */
    def this(conf: sparkconf, batchduration: duration) = {
      this(streamingcontext.createnewsparkcontext(conf), null, batchduration)
    }

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

    • 创建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()来停止)
    • 创建了streamingcontext后需要注意什么?
      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)
    • 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里面一个间隔包含的数据。

      Spark Streaming核心概念与编程

      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构成的。

      Spark Streaming核心概念与编程

    • 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的内存中。

      • spark支持两种数据源
        1. basic sources: file systems, and socket connections.
        2. advanced sources: kafka, flume

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操作差不多!

transformation meaning
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 operation meaning
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 依赖配置
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
        xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <groupid>org.ko</groupid>
  <version>1.0.0-snapshot</version>
  <modelversion>4.0.0</modelversion>
  <artifactid>spark-streaming</artifactid>
  <inceptionyear>2008</inceptionyear>
  <properties>
      <scala.version>2.11.12</scala.version>
      <kafka.version>2.0.0</kafka.version>
      <spark.version>2.2.1</spark.version>
      <hadoop.version>3.1.0</hadoop.version>
      <hbase.version>2.1.0</hbase.version>
      <jackson.version>2.9.2</jackson.version>
  </properties>

  <dependencies>
      <!--hadoop 依赖-->
      <dependency>
          <groupid>org.apache.hadoop</groupid>
          <artifactid>hadoop-client</artifactid>
          <version>${hadoop.version}</version>
      </dependency>

      <!--spark streaming 依赖-->
      <dependency>
          <groupid>org.apache.spark</groupid>
          <artifactid>spark-streaming_2.11</artifactid>
          <version>${spark.version}</version>
      </dependency>

      <!--hbase client 依赖-->
      <dependency>
          <groupid>org.apache.hbase</groupid>
          <artifactid>hbase-client</artifactid>
          <version>${hbase.version}</version>
      </dependency>

      <!--jackson json处理工具包-->
      <dependency>
          <groupid>com.fasterxml.jackson.module</groupid>
          <artifactid>jackson-module-scala_2.11</artifactid>
          <version>${jackson.version}</version>
      </dependency>

      <!--hbase server 依赖-->
      <!--<dependency>
          <groupid>org.apache.hbase</groupid>
          <artifactid>hbase-server</artifactid>
          <version>${hbase.version}</version>
      </dependency>-->

      <!--scala library-->
      <dependency>
          <groupid>org.scala-lang</groupid>
          <artifactid>scala-library</artifactid>
          <version>${scala.version}</version>
      </dependency>

      <!--kafka 依赖-->
      <dependency>
          <groupid>org.apache.kafka</groupid>
          <artifactid>kafka_2.11</artifactid>
          <version>${kafka.version}</version>
          <exclusions>
              <exclusion>
                  <groupid>org.xerial.snappy</groupid>
                  <artifactid>snappy-java</artifactid>
              </exclusion>
              <exclusion>
                  <groupid>com.fasterxml.jackson.core</groupid>
                  <artifactid>*</artifactid>
              </exclusion>
          </exclusions>
      </dependency>
      <dependency>
          <groupid>org.xerial.snappy</groupid>
          <artifactid>snappy-java</artifactid>
          <version>1.1.2.6</version>
      </dependency>
  </dependencies>

  <!--cdh hadoop repository-->
  <!--<repositories>
      <repository>
          <id>cloudera</id>
          <url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
      </repository>
  </repositories>-->

  <build>
      <sourcedirectory>src/main/scala</sourcedirectory>
      <testsourcedirectory>src/test/scala</testsourcedirectory>
      <plugins>
          <plugin>
              <groupid>org.scala-tools</groupid>
              <artifactid>maven-scala-plugin</artifactid>
              <version>2.15.1</version>
              <executions>
                  <execution>
                      <goals>
                          <goal>compile</goal>
                          <goal>testcompile</goal>
                      </goals>
                  </execution>
              </executions>
              <configuration>
                  <scalaversion>${scala.version}</scalaversion>
                  <args>
                      <arg>-target:jvm-1.5</arg>
                  </args>
              </configuration>
          </plugin>
          <plugin>
              <groupid>org.apache.maven.plugins</groupid>
              <artifactid>maven-eclipse-plugin</artifactid>
              <configuration>
                  <downloadsources>true</downloadsources>
                  <buildcommands>
                      <buildcommand>ch.epfl.lamp.sdt.core.scalabuilder</buildcommand>
                  </buildcommands>
                  <additionalprojectnatures>
                      <projectnature>ch.epfl.lamp.sdt.core.scalanature</projectnature>
                  </additionalprojectnatures>
                  <classpathcontainers>
                      <classpathcontainer>org.eclipse.jdt.launching.jre_container</classpathcontainer>
                      <classpathcontainer>ch.epfl.lamp.sdt.launching.scala_container</classpathcontainer>
                  </classpathcontainers>
              </configuration>
          </plugin>
          <plugin>
              <groupid>org.apache.maven.plugins</groupid>
              <artifactid>maven-compiler-plugin</artifactid>
              <configuration>
                  <source>8</source>
                  <target>8</target>
              </configuration>
          </plugin>
      </plugins>
  </build>
  <reporting>
      <plugins>
          <plugin>
              <groupid>org.scala-tools</groupid>
              <artifactid>maven-scala-plugin</artifactid>
              <configuration>
                  <scalaversion>${scala.version}</scalaversion>
              </configuration>
          </plugin>
      </plugins>
  </reporting>
</project>
  • spark streaming处理socket数据

    • 1.代码实现
    /**
      * spark streaming 处理socket数据
      *
      * 测试: nc -lk 6789
      */
    object networkwordcount {
    
      def main(args: array[string]): unit = {
        //1. 创建spark conf配置
        val sparkconf = new sparkconf()
          .setmaster("local[2]")
          .setappname("networkwordcount")
    
        //2. 创建streamingcontext需要两个参数: sparkconf 和 batch interval
        val ssc = new streamingcontext(sparkconf, seconds(5))
        val lines = ssc.sockettextstream("192.168.37.128", 6789)
    
        val result = lines.flatmap(_.split(" ")).map((_, 1)).reducebykey(_+_)
    
        result.print()
    
        ssc.start()
        ssc.awaittermination()
      }
    }
    • 2.为什么local[?], 一定要设置为2

    Spark Streaming核心概念与编程

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

  • spark streaming 处理 hdfs 文件数据

    • 代码实现
    /**
      * <p>
      *   使用spark streaming 处理文件系统(local/hdfs)的数据
      * </p>
      */
    object filewordcount {
    
      def main(args: array[string]): unit = {
        val sparkconf = new sparkconf()
          .setmaster("local")
          .setappname("filewordcount")
    
        val ssc = new streamingcontext(sparkconf, seconds(5))
    
        val lines = ssc.textfilestream("d:\\tmp")
    
        val result = lines.flatmap(_.split(" ")).map((_, 1)).reducebykey(_+_)
    
        result.print()
    
        ssc.start()
        ssc.awaittermination()
      }
    
    }

    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.(一但移动就不可以再改变,是持久的被添加进去,新写入数据不会被处理。)