object StreamSQLDemo1 {
case class Order(orderId:String,UserID:Int,money:Long,timestamp:Long)
def main(args: Array[String]): Unit = {
//1.构建flink的流处理运行环境
val env = StreamExecutionEnvironment.getExecutionEnvironment
//2.构建table的运行环境
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
val tableEnv = TableEnvironment.getTableEnvironment(env)
//3.创建订单数据通过addSource来生产数据,构建样例类来封装数据
val orderDataStream = env.addSource(new RichSourceFunction[Order] {
var isRunning= true
override def run(ctx: SourceFunction.SourceContext[Order]): Unit = {
while (isRunning){
val order = Order(UUID.randomUUID().toString,Random.nextInt(3),Random.nextInt(101),System.currentTimeMillis())
ctx.collect(order)
TimeUnit.SECONDS.sleep(1)
}
}
override def cancel(): Unit = {
isRunning= false
}
})
//4.添加水印
val waterMarkDataStream = orderDataStream.assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarks[Order] {
var currentTime:Long = _
val delayTime = 2000
//生产水印
override def getCurrentWatermark: Watermark = {
val watermark = new Watermark(currentTime - delayTime)
watermark
}
//获取订单时间
override def extractTimestamp(element: Order, previousElementTimestamp: Long): Long = {
val time = element.timestamp
currentTime = Math.max(currentTime,time)
currentTime
}
})
//5.注册成表,也要把各个字段进行输入,使用单引号'进行标记,同时需要将时间调用rowtime方法,
//导入隐式转换 import org.apache.flink.table.api.scala._
tableEnv.registerDataStream("orderTable",waterMarkDataStream,'orderId,'UserID,'money,'createTime.rowtime)
//6.编写sql,再sql中通过tumble(),指定事件时间,和指定窗口滑动时间 interval '' second
val sql =
"""
|select UserID,max(money) maxMoney,min(money) minMoney,count(1) orderNum from orderTable group by tumble(createTime,interval '3' second),
|UserID
""".stripMargin
//7.使用tableEnv.sqlQuery 来执行sql
val table = tableEnv.sqlQuery(sql)
//8.将查询的数据转换为DataStream,使用toAppendStream来转换,指定Row行泛型,
val resultDataStream = tableEnv.toAppendStream[Row](table)
//9.启动程序
resultDataStream.print()
env.execute("APP")
}
}
转载
https://blog.csdn.net/qq_36039236/article/details/108621968