当前位置:   article > 正文

大数据分析与内存计算学习笔记

大数据分析与内存计算学习笔记

一、Scala编程初级实践

1.计算级数:

请用脚本的方式编程计算并输出下列级数的前n项之和Sn,直到Sn刚好大于或等于q为止,其中q为大于0的整数,其值通过键盘输入。(不使用脚本执行方式可写Java代码转换成Scala代码执行)

fef3bb1accdc4bf9a0422f2d6f77126c.png

例如,若q的值为50.0,则输出应为:Sn=50.416695。

测试样例:

q=1时,Sn=2;

q=30时,Sn=30.891459;

q=50时,Sn=50.416695;

相关代码:

  1. import scala.io.StdIn.readInt
  2. object MedicalOne {
  3. def main(args: Array[String]): Unit = {
  4. var Sn: Float = 0
  5. var n: Float = 1
  6. println("please input q:")
  7. val q = readInt()
  8. while (Sn < q) {
  9. Sn += (n + 1) / n
  10. n += 1
  11. }
  12. if (Sn == Sn.toInt) {
  13. println(s"Sn=${Sn.toInt}")
  14. } else {
  15. println(s"Sn=$Sn")
  16. }
  17. }
  18. }

运行结果:

9d362d4934bb4ce9b9f4b4c704709c96.png

de5d8d3463f740c896cc633e723cc269.png

46497a05f263404e9f73dc7fe0743fb2.png

2 模拟图形绘制:

对于一个图形绘制程序,用下面的层次对各种实体进行抽象。定义一个Drawable的特质,其包括一个draw方法,默认实现为输出对象的字符串表示。定义一个Point类表示点,其混入了Drawable特质,并包含一个shift方法,用于移动点。所有图形实体的抽象类为Shape,其构造函数包括一个Point类型,表示图形的具体位置(具体意义对不同的具体图形不一样)。Shape类有一个具体方法moveTo和一个抽象方法zoom,其中moveTo将图形从当前位置移动到新的位置, 各种具体图形的moveTo可能会有不一样的地方。zoom方法实现对图形的放缩,接受一个浮点型的放缩倍数参数,不同具体图形放缩实现不一样。继承Shape类的具体图形类型包括直线类Line和圆类Circle。Line类的第一个参数表示其位置,第二个参数表示另一个端点,Line放缩的时候,其中点位置不变,长度按倍数放缩(注意,缩放时,其两个端点信息也改变了),另外,Line的move行为影响了另一个端点,需要对move方法进行重载。Circle类第一个参数表示其圆心,也是其位置,另一个参数表示其半径,Circle缩放的时候,位置参数不变,半径按倍数缩放。另外直线类Line和圆类Circle都混入了Drawable特质,要求对draw进行重载实现,其中类Line的draw输出的信息样式为“Line:第一个端点的坐标--第二个端点的坐标)”,类Circle的draw输出的信息样式为“Circle center:圆心坐标,R=半径”。如下的代码已经给出了Drawable和Point的定义,同时也给出了程序入口main函数的实现,请完成Shape类、Line类和Circle类的定义。

相关代码

代码目录:

a0b93f4a1b4b42ef9936d4412a56e508.png

主类GraphicPlotting:

  1. object GraphicPlotting {
  2. def main(args: Array[String]): Unit = {
  3. val p = Point(10, 30)
  4. p.draw()
  5. val line1 = new Line(Point(0, 0), Point(20, 20))
  6. line1.draw()
  7. line1.moveTo(Point(5, 5)) //移动到一个新的点
  8. line1.draw()
  9. line1.zoom(2) //放大两倍
  10. line1.draw()
  11. val cir = new Circle(Point(10, 10), 5)
  12. cir.draw()
  13. cir.moveTo(Point(30, 20))
  14. cir.draw()
  15. cir.zoom(0.5)
  16. cir.draw()
  17. }
  18. }

Drawable类

  1. trait Drawable {
  2. def draw() {
  3. println(this.toString)
  4. }
  5. }

Point类

  1. case class Point(var x: Double, var y: Double) extends Drawable {
  2. def shift(deltaX: Double, deltaY: Double) {
  3. x += deltaX;
  4. y += deltaY
  5. }
  6. }

Shape类

  1. abstract class Shape(var location: Point) {
  2. def moveTo(newLocation: Point) {
  3. location = newLocation
  4. }
  5. def zoom(scale: Double)
  6. }

Line类

  1. class Line(beginPoint: Point, var endPoint: Point) extends Shape(beginPoint) with Drawable {
  2. override def draw() {
  3. println(s"Line:(${location.x},${location.y})--(${endPoint.x},${endPoint.y})")
  4. } //按指定格式重载click
  5. override def moveTo(newLocation: Point) {
  6. endPoint.shift(newLocation.x - location.x, newLocation.y - location.y) //直线移动时,先移动另外一个端点
  7. location = newLocation //移动位置
  8. }
  9. override def zoom(scale: Double) {
  10. val midPoint = Point((endPoint.x + location.x) / 2, (endPoint.y + location.y) / 2) //求出中点,并按中点进行缩放
  11. location.x = midPoint.x + scale * (location.x - midPoint.x)
  12. location.y = midPoint.y + scale * (location.y - midPoint.y)
  13. endPoint.x = midPoint.x + scale * (endPoint.x - midPoint.x)
  14. endPoint.y = midPoint.y + scale * (endPoint.y - midPoint.y)
  15. }
  16. }

Circle类

  1. class Circle(center: Point, var radius: Double) extends Shape(center) with Drawable {
  2. override def draw() { //按指定格式重载click
  3. println(s"Circle center:(${location.x},${location.y}),R=$radius")
  4. }
  5. override def zoom(scale: Double) {
  6. radius = radius * scale //对圆的缩放只用修改半径
  7. }
  8. }

编译运行程序,期望的输出结果如下:

07eb9206bea04e9a854c14c45898873b.png

3 统计学生成绩:

学生的成绩清单格式如下所示,第一行为表头,各字段意思分别为学号、性别、课程名1、课程名2等,后面每一行代表一个学生的信息,各字段之间用空白符隔开

Id     gender Math    English   Physics   

301610    male   80      64        78

301611  female   65      87        58

...

给定任何一个如上格式的清单(不同清单里课程数量可能不一样),要求尽可能采用函数式编程,统计出各门课程的平均成绩,最低成绩,和最高成绩;另外还需按男女同学分开,分别统计各门课程的平均成绩,最低成绩,和最高成绩。

测试样例1如下:

Id     gender Math    English   Physics   

301610    male   80      64        78

301611  female   65      87        58

301612  female   44      71        77

301613  female   66      71        91

301614  female   70      71       100

301615    male   72      77        72

301616  female   73      81        75

301617  female   69      77        75

301618    male   73      61        65

301619    male   74      69        68

301620    male   76      62        76

301621    male   73      69        91

301622    male   55      69        61

301623    male   50      58        75

301624  female   63      83        93

301625    male   72      54       100

301626    male   76      66        73

301627    male   82      87        79

301628  female   62      80        54

301629    male   89      77        72

测试样例2如下:

Id     gender Math    English   Physics  Science

301610    male   72     39         74     93

301611    male   75     85         93     26

301612  female   85    79         91     57

301613  female   63    89         61     62

301614    male   72     63         58     64

301615    male   99     82         70     31

301616  female  100    81         63     72

301617    male   74    100         81     59

301618  female   68    72         63    100

301619    male   63     39         59     87

301620  female   84    88         48     48

301621    male   71     88         92     46

301622    male   82     49         66     78

301623    male   63     80         83     88

301624  female   86    80         56     69

301625    male   76     69         86     49

301626    male   91     59         93     51

301627  female   92    76         79    100

301628    male   79     89         78     57

301629    male   85     74         78     80

样例1的统计代码和结果输出

相关代码

  1. import scala.io.Source
  2. object Studentgrades_1 {
  3. def main(args: Array[String]): Unit = {
  4. val fileName = "D:\\IDEAProjects\\SecondScala\\src\\main\\scala\\grades1.txt"
  5. val lines = Source.fromFile(fileName).getLines().toList
  6. val header = lines.head.trim.split("\\s+").map(_.trim)
  7. val data = lines.tail.map(_.trim.split("\\s+"))
  8. val courseNames = header.drop(2)
  9. val statsTotal = calculateStatistics(data, courseNames)
  10. val statsMales = calculateStatistics(data.filter(_ (1) == "male"), courseNames)
  11. val statsFemales = calculateStatistics(data.filter(_ (1) == "female"), courseNames)
  12. printStatistics(statsTotal, "")
  13. printStatistics(statsMales, " (males)")
  14. printStatistics(statsFemales, " (females)")
  15. }
  16. def calculateStatistics(data: List[Array[String]], courses: Array[String]): List[(String, Double, Double, Double)] = {
  17. val courseScores = courses.indices.map { i =>
  18. val scores = data.filter(_(i + 2).matches("-?\\d+(\\.\\d+)?")).map(_(i + 2).toDouble) // Ensure we only have numbers
  19. if (scores.isEmpty) {
  20. (courses(i), 0.0, 0.0, 0.0) // Avoid division by zero if there are no scores for a course
  21. } else {
  22. val average = scores.sum / scores.length
  23. val min = scores.min
  24. val max = scores.max
  25. (courses(i), average, min, max)
  26. }
  27. }
  28. courseScores.toList
  29. }
  30. def printStatistics(stats: List[(String, Double, Double, Double)], title: String): Unit = {
  31. println(s"course average min max${title}")
  32. stats.foreach { case (course, average, min, max) =>
  33. println(f"$course: $average%.2f $min%.2f $max%.2f")
  34. }
  35. println()
  36. }
  37. }

结果输出

6310510c92c644f896d5ac7804a73aa0.png

样例1的统计代码和结果输出

相关代码

  1. import scala.io.Source
  2. object Studentgrades_2 {
  3. def main(args: Array[String]): Unit = {
  4. val fileName = "D:\\IDEAProjects\\SecondScala\\src\\main\\scala\\grades2.txt"
  5. val lines = Source.fromFile(fileName).getLines().toList
  6. val header = lines.head.trim.split("\\s+").map(_.trim)
  7. val data = lines.tail.map(_.trim.split("\\s+"))
  8. val courseNames = header.drop(2)
  9. val statsTotal = calculateStatistics(data, courseNames)
  10. val statsMales = calculateStatistics(data.filter(_ (1) == "male"), courseNames)
  11. val statsFemales = calculateStatistics(data.filter(_ (1) == "female"), courseNames)
  12. printStatistics(statsTotal, "")
  13. printStatistics(statsMales, " (males)")
  14. printStatistics(statsFemales, " (females)")
  15. }
  16. def calculateStatistics(data: List[Array[String]], courses: Array[String]): List[(String, Double, Double, Double)] = {
  17. val courseScores = courses.indices.map { i =>
  18. val scores = data.filter(_(i + 2).matches("-?\\d+(\\.\\d+)?")).map(_(i + 2).toDouble) // Ensure we only have numbers
  19. if (scores.isEmpty) {
  20. (courses(i), 0.0, 0.0, 0.0) // Avoid division by zero if there are no scores for a course
  21. } else {
  22. val average = scores.sum / scores.length
  23. val min = scores.min
  24. val max = scores.max
  25. (courses(i), average, min, max)
  26. }
  27. }
  28. courseScores.toList
  29. }
  30. def printStatistics(stats: List[(String, Double, Double, Double)], title: String): Unit = {
  31. println(s"course average min max")
  32. stats.foreach { case (course, average, min, max) =>
  33. println(f"$course: $average%.2f $min%.2f $max%.2f")
  34. }
  35. println()
  36. }
  37. }

结果输出

863901a5a3574a379fa6ddeb9959c63c.png

二、RDD编程初级实践

1.spark-shell交互式编程

使用chapter5-data1.txt,该数据集包含了某大学计算机系的成绩,数据格式如下所示:

Tom,DataBase,80

Tom,Algorithm,50

Tom,DataStructure,60

Jim,DataBase,90

Jim,Algorithm,60

Jim,DataStructure,80

……

请根据给定的实验数据,在spark-shell中通过编程来计算以下内容:

(1)该系总共有多少学生;

(2)该系共开设来多少门课程;

(3)Tom同学的总成绩平均分是多少;

(4)求每名同学的选修的课程门数;

(5)该系DataBase课程共有多少人选修;

(6)各门课程的平均分是多少;

(7)使用累加器计算共有多少人选了DataBase这门课。

相关代码:

  1. 1
  2. val lines = sc.textFile("file:///home/qiangzi/chapter5-data1.txt")
  3. val par = lines.map(row=>row.split(",")(0))
  4. val distinct_par = par.distinct() //去重操作
  5. distinct_par.count //取得总数
  6. 2
  7. val lines = sc.textFile("file:///home/qiangzi/chapter5-data1.txt")
  8. val par = lines.map(row=>row.split(",")(1))
  9. val distinct_par = par.distinct()
  10. distinct_par.count
  11. 3
  12. val lines = sc.textFile("file:///home/qiangzi/chapter5-data1.txt")
  13. val pare = lines.filter(row=>row.split(",")(0)=="Tom")
  14. pare.foreach(println)
  15. pare.map(row=>(row.split(",")(0),row.split(",")(2).toInt)).mapValues(x=>(x,1)).reduceByKey((x,y ) => (x._1+y._1,x._2 + y._2)).mapValues(x => (x._1 / x._2)).collect()
  16. 4
  17. val lines = sc.textFile("file:///home/qiangzi/chapter5-data1.txt")
  18. val pare = lines.map(row=>(row.split(",")(0),row.split(",")(1)))
  19. pare.mapValues(x => (x,1)).reduceByKey((x,y) => (" ",x._2 + y._2)).mapValues(x => x._2).foreach(println)
  20. 5
  21. val lines = sc.textFile("file:///home/qiangzi/chapter5-data1.txt")
  22. val pare = lines.filter(row=>row.split(",")(1)=="DataBase")
  23. pare.count
  24. 6
  25. val lines = sc.textFile("file:///home/qiangzi/chapter5-data1.txt")
  26. val pare = lines.map(row=>(row.split(",")(1),row.split(",")(2).toInt))
  27. pare.mapValues(x=>(x,1)).reduceByKey((x,y) => (x._1+y._1,x._2 + y._2)).mapValues(x => (x._1/ x._2)).collect().foreach(x => println(s"${x._1}: ${x._2}"))
  28. 7
  29. val lines = sc.textFile("file:///home/qiangzi/chapter5-data1.txt")
  30. val pare = lines.filter(row=>row.split(",")(1)=="DataBase").map(row=>(row.split(",")(1),1))
  31. val accum = sc.longAccumulator("My Accumulator")
  32. pare.values.foreach(x => accum.add(x))
  33. accum.value

2.编写独立应用程序实现数据去重

对于两个输入文件A和B,编写Spark独立应用程序,对两个文件进行合并,并剔除其中重复的内容,得到一个新文件C。下面是输入文件和输出文件的一个样例,供参考。

输入文件A的样例如下:

20170101    x

20170102    y

20170103    x

20170104    y

20170105    z

20170106    z

输入文件B的样例如下:

20170101    y

20170102    y

20170103    x

20170104    z

20170105    y

根据输入的文件A和B合并得到的输出文件C的样例如下:

20170101    x

20170101    y

20170102    y

20170103    x

20170104    y

20170104    z

20170105    y

20170105    z

20170106    z

实验代码:

  1. cd ~ # 进入用户主文件夹
  2. mkdir ./remdup
  3. mkdir -p ./remdup/src/main/scala
  4. vim ./remdup/src/main/scala/RemDup.scala
  5. /* RemDup.scala */
  6. import org.apache.spark.SparkContext
  7. import org.apache.spark.SparkContext._
  8. import org.apache.spark.SparkConf
  9. import org.apache.spark.HashPartitioner
  10. object RemDup {
  11. def main(args: Array[String]) {
  12. val conf = new SparkConf().setAppName("RemDup")
  13. val sc = new SparkContext(conf)
  14. val dataFileA = "file:///home/qiangzi/A.txt"
  15. val dataFileB = "file:///home/qiangzi/B.txt"
  16. val dataA = sc.textFile(dataFileA, 2)
  17. val dataB = sc.textFile(dataFileB, 2)
  18. val res = dataA.union(dataB).filter(_.trim().length > 0).map(line => (line.trim, "")).partitionBy(new HashPartitioner(1)).groupByKey().sortByKey().keys
  19. res.saveAsTextFile("file:///home/qiangzi/C.txt")
  20. }
  21. }
  22. cd ~/remdup
  23. vim simple.sbt
  24. /* simple.sbt*/
  25. name := "Simple Project"
  26. version := "1.0"
  27. scalaVersion := "2.12.18"
  28. libraryDependencies += "org.apache.spark" %% "spark-core" % "3.5.1"
  29. /usr/local/sbt-1.9.0/sbt/sbt package
  30. /usr/local/spark-3.5.1/bin/spark-submit --class "RemDup" --driver-java-options "-Dfile.encoding=UTF-8" ~/remdup/target/scala-2.12/simple-project_2.12-1.0.jar

3.编写独立应用程序实现求平均值问题

每个输入文件表示班级学生某个学科的成绩,每行内容由两个字段组成,第一个是学生名字,第二个是学生的成绩;编写Spark独立应用程序求出所有学生的平均成绩,并输出到一个新文件中。下面是输入文件和输出文件的一个样例,供参考。

Algorithm成绩:

小明 92

小红 87

小新 82

小丽 90

Database成绩:

小明 95

小红 81

小新 89

小丽 85

Python成绩:

小明 82

小红 83

小新 94

小丽 91

平均成绩如下:

    (小红,83.67)

    (小新,88.33)

    (小明,89.67)

    (小丽,88.67)

实验代码:

  1. cd ~ # 进入用户主文件夹
  2. mkdir ./avgscore
  3. mkdir -p ./avgscore/src/main/scala
  4. vim ./avgscore/src/main/scala/AvgScore.scala
  5. /* AvgScore.scala */
  6. import org.apache.spark.SparkContext
  7. import org.apache.spark.SparkContext._
  8. import org.apache.spark.SparkConf
  9. import org.apache.spark.HashPartitioner
  10. object AvgScore {
  11. def main(args: Array[String]) {
  12. val conf = new SparkConf().setAppName("AvgScore")
  13. val sc = new SparkContext(conf)
  14. val dataFiles = Array(
  15. "file:///home/qiangzi/Sparkdata/algorithm.txt",
  16. "file:///home/qiangzi/Sparkdata/database.txt",
  17. "file:///home/qiangzi/Sparkdata/python.txt"
  18. )
  19. val data = dataFiles.foldLeft(sc.emptyRDD[String]) { (acc, file) =>
  20. acc.union(sc.textFile(file, 3))
  21. }
  22. val res = data.filter(_.trim().length > 0).map(line => {
  23. val fields = line.split(" ")
  24. (fields(0).trim(), fields(1).trim().toInt)
  25. }).partitionBy(new HashPartitioner(1)).groupByKey().mapValues(x => {
  26. var n = 0
  27. var sum = 0.0
  28. for (i <- x) {
  29. sum += i
  30. n += 1
  31. }
  32. val avg = sum / n
  33. f"$avg%1.2f"
  34. })
  35. res.saveAsTextFile("file:///home/qiangzi/Sparkdata/average.txt")
  36. }
  37. }
  38. cd ~/avgscore
  39. vim simple.sbt
  40. /* simple.sbt*/
  41. name := "Simple Project"
  42. version := "1.0"
  43. scalaVersion := "2.12.18"
  44. libraryDependencies += "org.apache.spark" %% "spark-core" % "3.5.1"
  45. /usr/local/sbt-1.9.0/sbt/sbt package
  46. /usr/local/spark-3.5.1/bin/spark-submit --class "AvgScore" --driver-java-options "-Dfile.encoding=UTF-8" ~/avgscore/target/scala-2.12/simple-project_2.12-1.0.jar

三、Spark SQL编程初级实践

1.Spark SQL基本操作

将下列JSON格式数据复制到Linux系统中,并保存命名为employee.json。

{ "id":1 , "name":" Ella" , "age":36 }

{ "id":2, "name":"Bob","age":29 }

{ "id":3 , "name":"Jack","age":29 }

{ "id":4 , "name":"Jim","age":28 }

{ "id":4 , "name":"Jim","age":28 }

{ "id":5 , "name":"Damon" }

{ "id":5 , "name":"Damon" }

为employee.json创建DataFrame,并写出Scala语句完成下列操作:

  1. 查询所有数据;
  2. 查询所有数据,并去除重复的数据;
  3. 查询所有数据,打印时去除id字段;
  4. 筛选出age>30的记录;
  5. 将数据按age分组;
  6. 将数据按name升序排列;
  7. 取出前3行数据;
  8. 查询所有记录的name列,并为其取别名为username;
  9. 查询年龄age的平均值;
  10. 查询年龄age的最小值。

实验代码:

  1. 1
  2. import org.apache.spark.sql.SparkSession
  3. val spark=SparkSession.builder().getOrCreate()
  4. import spark.implicits._
  5. val df = spark.read.json("file:///home/qiangzi/employee.json")
  6. df.show()
  7. 2
  8. df.distinct().show()
  9. 3
  10. df.drop("id").show()
  11. 4
  12. df.filter(df("age") > 30 ).show()
  13. 5
  14. df.groupBy("age").count().show()
  15. 6
  16. df.sort(df("name").asc).show()
  17. 7
  18. df.take(3)
  19. 8
  20. df.select(df("name").as("username")).show()
  21. 9
  22. val avgAge = df.agg(avg("age")).first().getDouble(0)
  23. 10
  24. val minAge = df.agg(min("age")).first().getLong(0).toInt

2.编程实现将RDD转换为DataFrame

源文件内容如下(包含id,name,age):

1,Ella,36

2,Bob,29

3,Jack,29

       请将数据复制保存到Linux系统中,命名为employee.txt,实现从RDD转换得到DataFrame,并按“id:1,name:Ella,age:36”的格式打印出DataFrame的所有数据。请写出程序代码。

实验代码:

  1. cd ~ # 进入用户主文件夹
  2. mkdir ./rddtodf
  3. mkdir -p ./rddtodf/src/main/scala
  4. vim ./rddtodf/src/main/scala/RDDtoDF.scala
  5. /* RDDtoDF.scala */
  6. import org.apache.spark.sql.types._
  7. import org.apache.spark.sql.Encoder
  8. import org.apache.spark.sql.Row
  9. import org.apache.spark.sql.SparkSession
  10. object RDDtoDF {
  11. def main(args: Array[String]) {
  12. val spark = SparkSession.builder().appName("RDDtoDF").getOrCreate()
  13. import spark.implicits._
  14. val employeeRDD = spark.sparkContext.textFile("file:///home/qiangzi/employee.txt")
  15. val schemaString = "id name age"
  16. val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, nullable = true))
  17. val schema = StructType(fields)
  18. val rowRDD = employeeRDD.map(_.split(",")).map(attributes => Row(attributes(0).trim, attributes(1), attributes(2).trim))
  19. val employeeDF = spark.createDataFrame(rowRDD, schema)
  20. employeeDF.createOrReplaceTempView("employee")
  21. val results = spark.sql("SELECT id,name,age FROM employee")
  22. results.map(t => "id:" + t(0) + "," + "name:" + t(1) + "," + "age:" + t(2)).show()
  23. spark.stop()
  24. }
  25. }
  26. cd ~/rddtodf
  27. vim simple.sbt
  28. /*simple.sbt*/
  29. name := "Simple Project"
  30. version := "1.0"
  31. scalaVersion := "2.12.18"
  32. libraryDependencies ++= Seq(
  33. "org.apache.spark" %% "spark-core" % "3.5.1",
  34. "org.apache.spark" %% "spark-sql" % "3.5.1"
  35. )
  36. /usr/local/sbt-1.9.0/sbt/sbt package
  37. /usr/local/spark-3.5.1/bin/spark-submit --class "RDDtoDF" --driver-java-options "-Dfile.encoding=UTF-8" ~/rddtodf/target/scala-2.12/simple-project_2.12-1.0.jar

3.编程实现利用DataFrame读写MySQL的数据

(1)在MySQL数据库中新建数据库sparktest,再创建表employee,包含如表6-2所示的两行数据。

6-2 employee表原有数据

id

name

gender

Age

1

Alice

F

22

2

John

M

25

(2)配置Spark通过JDBC连接数据库MySQL,编程实现利用DataFrame插入如表6-3所示的两行数据到MySQL中,最后打印出age的最大值和age的总和。

6-3 employee表新增数据

id

name

gender

age

3

Mary

F

26

4

Tom

M

23

实验代码:

  1. mysql -u root -p
  2. create database sparktest;
  3. use sparktest;
  4. create table employee (id int(4), name char(20), gender char(4), age int(4));
  5. insert into employee values(1,'Alice','F',22);
  6. insert into employee values(2,'John','M',25);
  7. cd ~ # 进入用户主文件夹
  8. mkdir ./testmysql
  9. mkdir -p ./testmysql/src/main/scala
  10. vim ./testmysql/src/main/scala/TestMySQL.scala
  11. /* TestMySQL.scala */
  12. import java.util.Properties
  13. import org.apache.spark.sql.SparkSession
  14. import org.apache.spark.sql.functions._
  15. import org.apache.spark.sql.types._
  16. import org.apache.spark.sql.Row
  17. object TestMySQL {
  18. def main(args: Array[String]): Unit = {
  19. val spark = SparkSession.builder()
  20. .appName("TestMySQL")
  21. .getOrCreate()
  22. val employeeRDD = spark.sparkContext.parallelize(Array("3 Mary F 26", "4 Tom M 23"))
  23. .map(_.split(" "))
  24. val schema = StructType(List(
  25. StructField("id", IntegerType, true),
  26. StructField("name", StringType, true),
  27. StructField("gender", StringType, true),
  28. StructField("age", IntegerType, true)
  29. ))
  30. val rowRDD = employeeRDD.map(p => Row(p(0).toInt, p(1).trim, p(2).trim, p(3).toInt))
  31. val employeeDF = spark.createDataFrame(rowRDD, schema)
  32. val prop = new Properties()
  33. prop.put("user", "root")
  34. prop.put("password", "789456MLq")
  35. prop.put("driver", "com.mysql.jdbc.Driver")
  36. employeeDF.write
  37. .mode("append")
  38. .jdbc("jdbc:mysql://slave1:3306/sparktest", "sparktest.employee", prop)
  39. val jdbcDF = spark.read
  40. .format("jdbc")
  41. .option("url", "jdbc:mysql://slave1:3306/sparktest")
  42. .option("driver", "com.mysql.jdbc.Driver")
  43. .option("dbtable", "employee")
  44. .option("user", "root")
  45. .option("password", "789456MLq")
  46. .load()
  47. val aggregatedDF = jdbcDF.agg(
  48. max("age").alias("max_age"),
  49. sum("age").alias("total_age")
  50. )
  51. aggregatedDF.show()
  52. spark.stop()
  53. }
  54. }
  55. cd ~/testmysql
  56. vim simple.sbt
  57. /*simple.sbt*/
  58. name := "Simple Project"
  59. version := "1.0"
  60. scalaVersion := "2.12.18"
  61. libraryDependencies ++= Seq(
  62. "org.apache.spark" %% "spark-core" % "3.5.1",
  63. "org.apache.spark" %% "spark-sql" % "3.5.1"
  64. )
  65. /usr/local/sbt-1.9.0/sbt/sbt package
  66. sudo /usr/local/spark-3.5.1/bin/spark-submit --class "TestMySQL" --driver-java-options "-Dfile.encoding=UTF-8" --jars /usr/local/hive-3.1.2/lib/mysql-connector-java-5.1.49.jar ~/testmysql/target/scala-2.12/simple-project_2.12-1.0.jar

四、Spark Streaming编程初级实践

1.实验目的

  • 通过实验学习使用Scala编程实现文件和数据的生成;
  • 掌握使用文件作为Spark Streaming数据源的编程方法

2.实验内容

(1)、以随机时间间隔在一个目录下生成大量文件,文件名随机命名,文件中包含随机生成的一些英文语句,每个英语语句内部的单词之间用空格隔开。

(2)、实时统计每10秒新出现的单词数量。

(3)、实时统计最近1分钟内每个单词的出现次数(每10秒统计1次)。

(4)、实时统计每个单词累计出现次数,并将结果保存到本地文件(每10秒统计1次)。

3.注意

        本次实验中,实验(2)、(3)、(4)是在实验(1)的基础之上做的,因为要做流计算,所以实验(2)、(3)、(4)在打包完运行代码之前,一定要先执行(1)代码,具体步骤如下:

  • 创建好所需目录后,打开两个终端(也可以安装idea,<1>在idea中运行,<2>,<3>,<4>在终端运行),一个执行实验(1)代码,一个执行实验(2)、(3)、(4)
  • 在实验(2)、(3)、(4)打包完以后,先执行实验(1)代码,然后再执行(2)、(3)、(4)

3.实验代码

(1)

  1. /*===================================================*/
  2. 这一部分代码,我是在idea中运行的,你也可以开两个终端,在其中
  3. 一个打包运行,
  4. /*===================================================*/
  5. import java.io.{File, PrintWriter}
  6. object GenFile{
  7. def main(args: Array[String]) {
  8. val strList = List(
  9. "There are three famous bigdata softwares",
  10. "and they are widely used in real applications",
  11. "For in that sleep of death what dreams may come",
  12. "The slings and arrows of outrageous fortune",
  13. "When we have shuffled off this mortal coil",
  14. "For who would bear the whips and scorns of time",
  15. "That patient merit of the unworthy takes",
  16. "When he himself might his quietus make",
  17. "To grunt and sweat under a weary life",
  18. "But that the dread of something after death",
  19. "And makes us rather bear those ills we have",
  20. "Than fly to others that we know not of",
  21. "Thus conscience does make cowards of us all",
  22. "And thus the native hue of resolution",
  23. "And enterprises of great pith and moment",
  24. "And lose the name of action"
  25. )
  26. var i = 0
  27. while (i < 10000){
  28. Thread.sleep(scala.util.Random.nextInt(5000))
  29. // 生成一个0到999之间的随机数,并转换为字符串
  30. var str = scala.util.Random.nextInt(1000).toString
  31. val filePath = "/home/qiangzi/data/out"+str+".txt"
  32. // 创建PrintWriter对象,用于写入文件
  33. val out = new PrintWriter(new File(filePath))
  34. // 随机选择列表中的句子并写入文件
  35. for (m <- 0 to 3) out.println(strList(scala.util.Random.nextInt(14)))
  36. out.close
  37. i = i + 1
  38. }
  39. }
  40. }

(2)

  1. cd
  2. mkdir ./wordcount
  3. mkdir -p ./wordcount/src/main/scala
  4. vim ./wordcount/src/main/scala/WordCount.scala
  5. /* WordCount.scala*/
  6. import org.apache.spark._
  7. import org.apache.spark.streaming._
  8. import org.apache.spark.SparkContext._
  9. object WordCount{
  10. def main(args: Array[String]) {
  11. val sparkConf = new SparkConf().setAppName("WordCount").setMaster("local[2]")
  12. //设置为本地运行模式,两个线程,一个监听,另一个处理数据
  13. val sc = new SparkContext(sparkConf)
  14. sc.setLogLevel("ERROR")
  15. val ssc = new StreamingContext(sc, Seconds(10)) // 时间间隔为10秒
  16. val lines = ssc.textFileStream("file:///home/qiangzi/data") // 设置文件流监控的目录
  17. val words = lines.flatMap(_.split(" "))
  18. val wordCounts = words.count()
  19. wordCounts.print()
  20. ssc.start()
  21. ssc.awaitTermination()
  22. }
  23. }
  24. cd ~/wordcount
  25. vim simple.sbt
  26. /*simple.sbt*/
  27. name := "Simple Project"
  28. version := "1.0"
  29. scalaVersion := "2.12.18"
  30. libraryDependencies ++= Seq(
  31. "org.apache.spark" %% "spark-core" % "3.5.1",
  32. "org.apache.spark" %% "spark-sql" % "3.5.1",
  33. "org.apache.spark" %% "spark-streaming" % "3.5.1" // 添加spark-streaming依赖
  34. )
  35. /usr/local/sbt-1.9.0/sbt/sbt package
  36. /usr/local/spark-3.5.1/bin/spark-submit --class "WordCount" --driver-java-options "-Dfile.encoding=UTF-8" ~/wordcount/target/scala-2.12/simple-project_2.12-1.0.jar

(3)

  1. cd
  2. mkdir ./wordcount1
  3. mkdir -p ./wordcount1/src/main/scala
  4. vim ./wordcount1/src/main/scala/WordCountOne.scala
  5. import org.apache.spark._
  6. import org.apache.spark.streaming._
  7. import org.apache.spark.SparkContext._
  8. import org.apache.spark.streaming.StreamingContext._
  9. object WordCount {
  10. def main(args: Array[String]) {
  11. // 设置Spark配置,应用程序名为"WordCountMinute",并设置本地模式运行,使用2个线程
  12. val sparkConf = new SparkConf().setAppName("WordCountMinute").setMaster("local[2]")
  13. val sc = new SparkContext(sparkConf)
  14. sc.setLogLevel("ERROR")
  15. // 创建StreamingContext对象,设置批处理间隔为10秒
  16. val ssc = new StreamingContext(sc, Seconds(10))
  17. // 设置数据源为文件流,监控指定目录下的文件变化
  18. val lines = ssc.textFileStream("file:///home/qiangzi/data")
  19. // 将每行文本分割成单词
  20. val words = lines.flatMap(_.split(" "))
  21. // 创建一个窗口化的DStream,窗口大小为60秒,滑动间隔为10秒
  22. val windowedWords = words.window(Seconds(60), Seconds(10))
  23. val wordCounts = windowedWords.flatMap(word => Array((word, 1)))
  24. .reduceByKey(_ + _)
  25. var outputCount = 0
  26. // 对每个RDD进行操作,打印每个单词的计数
  27. wordCounts.foreachRDD { rdd =>
  28. // 增加输出计数
  29. outputCount += 1
  30. // 获取当前系统时间的毫秒数
  31. val currentTime = System.currentTimeMillis()
  32. println(s"-------------------------------------------")
  33. println(s"Time: $currentTime ms")
  34. println(s"-------------------------------------------")
  35. // 遍历RDD中的每个元素,打印单词和对应的计数
  36. rdd.foreach { case (word, count) =>
  37. println(s"$word: $count")
  38. }
  39. // 如果输出次数达到6次,则停止SparkContext和StreamingContext
  40. if (outputCount == 6) {
  41. println("Finished printing word counts for the last time.")
  42. ssc.stop(stopSparkContext = true, stopGracefully = true)
  43. }
  44. }
  45. ssc.start()
  46. ssc.awaitTermination()
  47. }
  48. }
  49. cd ~/wordcount1
  50. vim simple.sbt
  51. /*simple.sbt*/
  52. name := "Simple Project"
  53. version := "1.0"
  54. scalaVersion := "2.12.18"
  55. libraryDependencies ++= Seq(
  56. "org.apache.spark" %% "spark-core" % "3.5.1",
  57. "org.apache.spark" %% "spark-sql" % "3.5.1",
  58. "org.apache.spark" %% "spark-streaming" % "3.5.1" // 添加spark-streaming依赖
  59. )
  60. /usr/local/sbt-1.9.0/sbt/sbt package
  61. /usr/local/spark-3.5.1/bin/spark-submit --class "WordCountOne" --driver-java-options "-Dfile.encoding=UTF-8" ~/wordcount1/target/scala-2.12/simple-project_2.12-1.0.jar

(4)

  1. cd
  2. mkdir ./wordcount2
  3. mkdir -p ./wordcount2/src/main/scala
  4. vim ./wordcount2/src/main/scala/WordCountTwo.scala
  5. import org.apache.spark._
  6. import org.apache.spark.streaming._
  7. import org.apache.spark.SparkContext._
  8. import org.apache.spark.streaming.StreamingContext._
  9. import java.text.SimpleDateFormat
  10. import java.util.Date
  11. object WordCountWithFileOutput {
  12. def main(args: Array[String]) {
  13. val sparkConf = new SparkConf().setAppName("WordCountWithFileOutput") .setMaster("local[2]") // 设置本地模式,使用2个线程
  14. val sc = new SparkContext(sparkConf) // 创建Spark上下文
  15. sc.setLogLevel("ERROR")
  16. val ssc = new StreamingContext(sc, Seconds(10)) // 创建Streaming上下文,设置批处理时间为10秒
  17. val lines = ssc.textFileStream("file:///home/qiangzi/data") // 监听目录,读取新增文件作为数据流
  18. val words = lines.flatMap(_.split(" ")) // 每行数据按空格切分,展平为单词流
  19. // 设置滑动窗口为6000秒长度,每10秒滑动一次(此处长度设置可能过大,实际使用中请根据需求调整)
  20. val windowedWords = words.window(Seconds(6000), Seconds(10))
  21. val wordCounts = windowedWords.flatMap(word => Array((word, 1))) .reduceByKey(_ + _) // 按单词聚合计数
  22. var outputCount = 0
  23. wordCounts.foreachRDD { rdd =>
  24. outputCount += 1
  25. val sdf = new SimpleDateFormat("yyyyMMdd_HHmmss") // 创建日期格式化对象
  26. val currentTimeStr = sdf.format(new Date(System.currentTimeMillis()))
  27. // 遍历RDD,将每个单词及其计数写入文件
  28. rdd.foreach { case (word, count) =>
  29. val outputFile = s"/home/qiangzi/dataout/${currentTimeStr}_wordcount.txt" // 构造输出文件路径
  30. val content = s"$word: $count\n"
  31. val bw = new java.io.BufferedWriter(new java.io.FileWriter(outputFile, true)) // 创建写入文件的对象
  32. bw.write(content)
  33. bw.close()
  34. }
  35. // 当输出计数达到600次时,停止SparkContext和StreamingContext
  36. if (outputCount == 600) {
  37. println("Finished writing word counts to files for the last time.")
  38. ssc.stop(stopSparkContext = true, stopGracefully = true)
  39. }
  40. }
  41. ssc.start()
  42. ssc.awaitTermination()
  43. }
  44. }
  45. cd ./wordcount2
  46. vim simple.sbt
  47. /*simple.sbt*/
  48. name := "Simple Project"
  49. version := "1.0"
  50. scalaVersion := "2.12.18"
  51. libraryDependencies ++= Seq(
  52. "org.apache.spark" %% "spark-core" % "3.5.1",
  53. "org.apache.spark" %% "spark-sql" % "3.5.1",
  54. "org.apache.spark" %% "spark-streaming" % "3.5.1" // 添加spark-streaming依赖
  55. )
  56. /usr/local/sbt-1.9.0/sbt/sbt package
  57. /usr/local/spark-3.5.1/bin/spark-submit --class "WordCountWithFileOutput" --driver-java-options "-Dfile.encoding=UTF-8" ~/wordcount2/target/scala-2.12/simple-project_2.12-1.0.jar

五、

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/519735
推荐阅读
相关标签
  

闽ICP备14008679号