学习致谢
https://www.bilibili.com/video/BV1Xz4y1m7cv?p=71
代码实现
package structured
import org.apache.spark.sql.{DataFrame, Dataset, Row, SparkSession}
/**
* Author itcast
* Desc 演示StructuredStreaming的SOURCE-Socket
*/
object Demo02_Source_Socket {
def main(args: Array[String]): Unit = {
//TODO 0.创建环境
//因为StructuredStreaming基于SparkSQL的且编程API/数据抽象是DataFrame/DataSet,所以这里创建SparkSession即可
val spark = SparkSession.builder().appName("sparksql").master("local[*]")
.config("spark.sql.shuffle.partitions","4").getOrCreate()//本次测试时分区数设置小一点,实际开发中可以根据集群规模设置大小
val sc = spark.sparkContext
sc.setLogLevel("WARN")
import spark.implicits._
import org.apache.spark.sql.functions._
//todo.1.加载数据
val df: DataFrame = spark.readStream.format("socket")
.option("host", "node1")
.option("port", 9999)
.load()
df.printSchema()
//df.show()// Queries with streaming sources must be executed with writeStream.start();
//todo.2.处理数据
val ds: Dataset[String] = df.as[String]
val result: Dataset[Row] = ds.flatMap(_.split(" "))
.groupBy('value)
.count()
.orderBy('count.desc)
//todo.3.输出结果
result.writeStream
.format("console")
.outputMode("complete")
//todo.4.启动并等待结束
.start()
.awaitTermination()
//todo.5.关闭资源
spark.stop()
}
}