本节介绍如何编写 Spark Streaming 应用程序,由简到难讲解使用几个核心概念来解决实际应用问题。
流数据模拟器
在实例演示中模拟实际情况,需要源源不断地接入流数据,为了在演示过程中更接近真实环境,首先需要定义流数据模拟器。该模拟器的主要功能是通过 Socket 方式监听指定的端口号,当外部程序通过该端口进行连接并请求数据时,模拟器将定时将指定的文件数据进行随机获取,并发送给外部程序。
流数据模拟器的代码如下。
- import java.io.{PrintWriter}
- import java.net.ServerSocket
- import scala.io.Source
- object StreamingSimulation {
- //定义随机获取整数的方法
- def index(length:Int) = {
- import java.util.Random
- val rdm = new Random
- rdm.nextInt(length)
- }
- def main(args: Array[String]) {
- //调用该模拟器需要 3 个参数,分别为文件路径、端口号和间隔时间(单位为毫秒)
- if (args.length != 3) {
- System.err.printIn(“Usage:<filename> <port><millisecond>”)
- System.exit(1)
- }
- //获取指定文件总的行数
- val filename = args(0)
- val lines = Source.fromFile(filename).getLines.toList
- val filerow = lines.length
- //指定监听某端口,当外部程序请求时建立连接
- val listener = new ServerSocket(args(1).toInt)
- while (true) {
- val socket = listener.accept()
- new Thread() {
- override def run = {
- printIn(“Got client connected from: “ + socket.getInetAddress)
- val out = new PrintWriter(socket.getOutputStream(), true)
- while (true) {
- Thread.sleep(args(2).toLong)
- //当该端口接受请求时,随机获取某行数据发送给对方
- val content = lines(index(filerow))
- printIn(content)
- out.write(content + ‘n‘) out.flush()
- }
- socket.close()
- }
- }.start()
- }
- }
- }
在 IDEA 开发环境打包配置界面中:
- 首先需要在 ClassPath 加入 Jar 包(/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)。
- 然后单击“Build”→“Build Artifacts”,选择“Build”或者“Rebuild”动作。