Spark Streaming programming combat (development instance)

This section describes how to write Spark Streaming applications, from simple to difficult to explain the use of several core concepts to solve practical problems.

Data stream simulators

In the simulation example demonstrates the actual situation, it is necessary to access to a steady stream of data stream, for a more realistic environment during the presentation, first need to define the data flow simulator. The main function of the simulator is monitored through the port number specified Socket embodiment, when the external program are connected through the port, and the requested data, the timing simulator specified file random data acquisition, and sends an external program.

A code stream data simulator follows.

  1. import java.io.{PrintWriter}
  2. import java.net.ServerSocket
  3. import scala.io.Source
  4.  
  5. object StreamingSimulation {
  6.  
  7. // define methods to obtain random integers
  8. def index(length:Int) = {
  9. import java.util.Random
  10. val rdm = new Random
  11. rdm.nextInt(length)
  12. }
  13.  
  14. def main(args: Array[String]) {
  15. // call the simulator requires three parameters, namely, the file path, port number, and the time interval (in milliseconds)
  16. if (args.length != 3) {
  17. System.err.printIn(“Usage:<filename> <port><millisecond>”)
  18. System.exit(1)
  19. }
  20.  
  21. // Get the total number of rows in the specified file
  22. val filename = args(0)
  23. val lines = Source.fromFile(filename).getLines.toList
  24. val filerow = lines.length
  25.  
  26. // Specify a monitor port, external connection is established when a program requests
  27. val listener = new ServerSocket(args(1).toInt)
  28. while (true) {
  29. val socket = listener.accept()
  30. new Thread() {
  31. override def run = {
  32. printIn(“Got client connected from: “ + socket.getInetAddress)
  33. val out = new PrintWriter(socket.getOutputStream(), true)
  34. while (true) {
  35. Thread.sleep(args(2).toLong)
  36. // when the port accepts the request, acquiring a random data transmission line to each other
  37. val content = lines(index(filerow))
  38. printIn(content)
  39. out.write(content + ‘n‘) out.flush()
  40. }
  41. socket.close()
  42. }
  43. }.start()
  44. }
  45. }
  46. }

IDEA development environment in the package configuration interface:

  • First need to add Jar package in ClassPath (/app/scala-2.10.4/lib/scala-swing.jar/app/scala-2.10.4/lib/scala-library.jar/app/scala-2.10.4/lib /scala-actors.jar).
  • Then click the "Build" → "Build Artifacts", select "Build" or "Rebuild" action.
  • Finally, copy the packed files to the root directory using the following command Spark.

cd /home/hadoop/IdeaProjects/out/artifacts/LearnSpark_jar
cp LearnSpark.jar /app/hadoop/spark-1.1.0/

Example 1: read the file demo

In this instance, Spark Streaming will monitor the files in a directory, access to data in the interval period of change, and then calculate the word count of the number of time periods by Spark Streaming.

Code is as follows.

  1. import org.apache.spark.SparkConf
  2. import org.apache.spark.streaming.{Seconds,StreamingContext}
  3. import org.apache.spark.streaming.StreamingContext._
  4.  
  5. object FileWordCount {
  6. def main(args:Array[String]) {
  7. selection sparkConf = new SparkConf (). setAppName ( "File Word Count"). setMaster ( "local" [2])
  8.  
  9. Streaming // create a context, the configuration and including Spark interval, where the time interval is 20 seconds val ssc = new StreamingContext (sparkConf, Seconds (20))
  10. // Specify monitored directory, where is / home / hadoop / temp /
  11. val lines = ssc.textFileStream(“/home/hadoop/temp/”)
  12. // to change the data in the specified folder and will be printed word count
  13. val words = lines.flatMap (_.split(“”))
  14. val wordCounts = words.map(x => (x, 1)).reduceByKey(_+_)
  15. wordCounts.print()
  16. // Start Streaming
  17. ssc.start()
  18. ssc.awaitTermination ()
  19. }
  20. }

To run the code there are three steps.

1) Create a Streaming Monitoring directory.

Creating / home / hadoop / temp directory Spark Streaming monitored, timed to add in the directory file, then the statistics of the number of words in documents newly added by Spark Streaming.

2) Use the following command to start the Spark cluster.

$cd /app/hadoop/spark-1.1.0
$sbin/start-all.sh

3) Run Streaming in IDEA program.

IDEA run in this example, since this example it does not require no input parameters configuration parameters, the timestamp in the time print run log. If you add a file monitoring directory, while the output of the output timestamp word counting the number of newly added file for that time period.

Example 2: Network data presentation

In this example, the data stream will be transmitted at a frequency simulator 1 second analog data, Spark Streaming Socket stream data received once every 20 seconds and run to process the data received, the period of time after the print data processed appears frequency, i.e. there is no relationship between the state of each processing period of time.

Code is as follows.

  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(20))
  11.  
  12. // get the data through Socket, need to provide the host name and port number Socket, the data stored in the memory and hard drive
  13. val lines =ssc.socketTextStream(args(0),args(1).toInt,StorageLevel.MEMORY_AND_DISK_SER)
  14.  
  15. // read the data is divided into the count
  16. val words = lines.flatMap(_.split(“,”))
  17. val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _) wordCounts.print()
  18. ssc.start()
  19. ssc.awaitTermination ()
  20. }
  21. }

To run the code in a total of four steps.

1) Start data stream simulator.

Start streaming data simulator, the simulator Socket port number is 9999, the frequency is 1 second. Sending / home / hadoop people.txt data files under / upload / class7 the directory in the example, wherein the content data people.txt follows.

1 Michael
2 Andy
3 Justin
4

Start command stream data simulator follows.

$cd /app/hadoop/spark-1.1.0
$java -cp LearnSpark.jar class7.StreamingSimulation
/home/hadoop/upload/class7/people.txt 9999 1000

When the program is not connected, the program is blocked.

2) Run Streaming in IDEA program.

IDEA run in this example, the need to configure the host name and port number of the Socket connection, in the configuration where the host name hadoop1, port number 9999.

3) Observation simulator transmission situation.

Spark Streaming IDEA program established in connection with the simulator, the simulator is detected when the test swab start sending data external connection, random data row of data acquired in the designated file, the time interval is 1 second. Figure 1 is a screenshot simulator transmission situation.

Screenshot simulator transmission case
Screenshot simulator transmission case 1

4) observation of statistical results.

In the IDEA operating window, the statistics can be observed. By analysis, the number of words within each period of 20 Spark Streaming, just transmitted is the sum of the number per 20 seconds.

—————————
Time:14369195400000ms
(Andy,2)
(Michael,9)
(Justin,9)

Examples 3: Stateful demo

This example is a Spark Streaming state operation, the stream data transmitted from the simulator to simulate one second frequency data, receiving Spark Streaming Socket stream data every five seconds and run to process the data received, the printing process starts after processing after the frequency of word appears.

That is, not only the output results of each statistical data received during this period, all previous data further includes period. With Comparative Example 2, in this example, between the states of the relevant time period.

Code is as follows.

  1. import org.apache.log4j.{Level,Logger}
  2. import org.apache.spark. SparkContext {,} SparkConf
  3. import org.apache.spark.streaming.{Seconds,StreamingContext}
  4. import org.apache.spark.streaming.StreamingContext._
  5.  
  6. object StatefulWordCount {
  7. def main(args: Array[String]) {
  8. if (args.length != 2) {
  9. System.err.printIn(“Usage: StatefulWordCount <filename> <port> “)
  10. System.exit(1)
  11. }
  12. Logger.getLogger(“org.apache.spark”).setLevel(Level.ERROR)
  13. Logger.getLogger(“org.eclipse.jetty.server”).setLevel(Level.OFF)
  14. // definition of the update state method, the parameter values ​​for the current batch word frequency, state word for the previous cycle, the frequency of
  15. val updateFunc = (values: Seq[Int],state: Option[Int]) => {
  16. val currentCount = values.foldLeft(0)(_ + _)
  17. val previousCount = state.getOrElse (0)
  18. Some(currentCount + previousCount)
  19. }
  20. val conf = new SparkConf().setAppName(“StatefulWordCount”).setMaster(“local[2]”)
  21. val sc = new SparkContext(conf)
  22. // Create StreamingContext, Spark Steaming run at intervals of 5 seconds
  23. val ssc = new StreamingContext(sc, Seconds(5))
  24. // Define checkpoint directory of the current directory
  25. ssc.checkpoint(“.”)
  26. // Get the data is sent over from Socket
  27. val lines = ssc.socketTextStream(args(0),args(1).toInt)
  28. val words = lines.flatMap(_.split(“.” ))
  29. val wordCounts = words.map(x => (x, 1))
  30.  
  31. // use updateStateByKey to update the status, the total number of statistical word
  32. val stateDstream = wordCounts.updateStateByKey[Int](updateFunc)
  33. stateDstream.print()
  34. ssc.start()
  35. ssc.awaitTermination ()
  36. }
  37. }

And the same process to Example 2 starting application IDEA start the data stream simulator.

See IDEA running window of the operation, the total number of words can be observed for the first time count is 0, the second five, the first N times is 5 (N-1), i.e., total number of words for programs running count the number of words Sum.

———————-
Time:14369196110000ms
———————-

———————-
Time:14369196150000ms
———————-
(Andy,2)
(Michael, 1)
(Justin,2)

Example 4: Window demo

This example is a Spark Streaming window operations, the data stream transmitted by the simulator frequency of 1 second analog data, the data stream received by Spark Streaming Socket run once every 10 seconds and to process the data received, the printing process starts after processing after the frequency of word appears.

Compared to the previous examples, Spark Streaming statistically window () method by reduceByKeyAndWindow, and specify the length of the sliding window time interval in this method.

Code is as follows:

  1. import org.apache.log4j.{Level,Logger}
  2. import org.apache.spark. SparkContext {,} SparkConf
  3. import org.apache.spark.storage.StorageLevel
  4. import org.apache.spark.streaming._
  5. import org.apache.spark.streaming.StreamingContext._
  6.  
  7. object StatefulWordCount {
  8. def main(args: Array[String]) {
  9. if (args.length != 4) {
  10. System.err.printIn(“Usage: StatefulWordCount <filename> <port><WindowDuration><slideDuration>
  11. “)
  12. System.exit(1)
  13. }
  14. Logger.getLogger(“org.apache.spark”).setLevel(Level.ERROR)
  15. Logger.getLogger(“org.eclipse.jetty.server”).setLevel(Level.OFF)
  16.  
  17. val conf = new SparkConf().setAppName(“WindowWordCount”).setMaster(“local[2]”)
  18. val sc = new SparkContext(conf)
  19. // Create StreamingContext
  20. val ssc = new StreamingContext(sc, Seconds(5))
  21. // Define checkpoint directory of the current directory
  22. ssc.checkpoint(“.”)
  23. // get the data through Socket, must provide the host name and port number Socket, the data stored in the memory and hard drive
  24. val lines = ssc.socketTextStream(args(0),args(1).toInt,StorageLevel.MEMORY_ONLY_SER)
  25. val words = lines.flatMap(_.split(“.” ))
  26. // Windows operation, the first way to overlay process, the second approach is incremental processing
  27. val wordCounts = words.map(x => (x, 1)).reduceByKeyAndWindow(_+_,_–_,Seconds(args(2).toInt),Seconds(srg3).toInt)
  28. wordCounts.print()
  29. ssc.start()
  30. ssc.awaitTermination ()
  31. }
  32. }

And the same process to Example 2 starting application IDEA start the data stream simulator.

IDEA running window, the total number of words can be observed for the statistical first 4, second 14, N th is 10 (Nl) +4, the total number of words or statistical run is the total number of words.

———————-
Time:14369196740000ms
———————-
(Andy,1)
(Michael, 2)
(Justin,1)

———————-
Time:14369196750000ms
———————-
(Andy,4)
(Michael, 5)
(Justin,5)

Recommended Learning Catalog:. 47 the Spark DSTREAM related operations
48. The the Spark Streaming development examples
49. Data Mining Introduction
50. The the Spark MLlib
51. The classification of data mining and predictive
52. The decision trees and naive Bayes algorithm

Guess you like

Origin blog.csdn.net/dsdaasaaa/article/details/94181640