Flink 输出至 MySql

【1】引入 pom 依赖,我的 Mysql版本为 5.7.19

1 <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
2 <dependency>
3     <groupId>mysql</groupId>
4     <artifactId>mysql-connector-java</artifactId>
5     <version>5.1.47</version>
6 </dependency>

【2】在 MySQL 中创建需要的数据源[flink]和表,表结构如下:

 1 SET NAMES utf8mb4;
 2 SET FOREIGN_KEY_CHECKS = 0;
 3 
 4 -- ----------------------------
 5 -- Table structure for temperatures
 6 -- ----------------------------
 7 DROP TABLE IF EXISTS `temperatures`;
 8 CREATE TABLE `temperatures`  (
 9   `sensor` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
10   `temp` double(60, 0) NULL DEFAULT NULL
11 ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
12 
13 SET FOREIGN_KEY_CHECKS = 1;

【3】Flink 输出至 MySql Scala 代码,自动导入的 scala包需要修改为 scala._ 否则会出现错误。

 1 package com.zzx.flink
 2 
 3 import java.sql.{Connection, DriverManager, PreparedStatement}
 4 
 5 import org.apache.flink.configuration.Configuration
 6 import org.apache.flink.streaming.api.functions.sink.{RichSinkFunction, SinkFunction}
 7 import org.apache.flink.streaming.api.scala._
 8 
 9 object MySqlSinkTest {
10   def main(args: Array[String]): Unit = {
11       // 创建一个流处理执行环境
12       val env = StreamExecutionEnvironment.getExecutionEnvironment
13       //从文件中读取数据并转换为 类
14       val inputStreamFromFile: DataStream[String] = env.readTextFile("E:\\Project\\flink\\src\\main\\resources\\wordcount.txt")
15       //转换
16       val dataStream: DataStream[SensorReading] = inputStreamFromFile
17         .map( data => {
18           var dataArray = data.split(",")
19           SensorReading(dataArray(0),dataArray(1).toLong,dataArray(2).toDouble)
20         })
21       dataStream.addSink(new MyJdbcSink())
22       env.execute("mysql sink test")
23   }
24 }
25 
26 class MyJdbcSink() extends RichSinkFunction[SensorReading]{
27   //初始化时建立连接,与编译器
28   var conn: Connection = _
29   var insertStmt: PreparedStatement = _
30   var updateSmt: PreparedStatement = _
31   //初始化,创建连接和预编译语句
32   override def open(parameters: Configuration): Unit = {
33     super.open(parameters)
34     conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/flink","root","root")
35     insertStmt = conn.prepareStatement("INSERT INTO temperatures(sensor,temp) VALUES(?,?) ")
36     updateSmt = conn.prepareStatement("UPDATE temperatures SET temp = ? WHERE sensor = ?")
37   }
38 
39   //调用连接执行 sql
40   override def invoke(value: SensorReading, context: SinkFunction.Context[_]): Unit = {
41    //执行更新语句,如果没更新,就进行插入
42     updateSmt.setDouble(1,value.temperature)
43     updateSmt.setString(2,value.id)
44     updateSmt.execute()
45     //如果update没有查到数据,那么执行插入语句
46     if(updateSmt.getUpdateCount == 0){
47       insertStmt.setDouble(2,value.temperature)
48       insertStmt.setString(1,value.id)
49       insertStmt.execute()
50     }
51   }
52 
53   //关闭资源
54   override def close(): Unit = {
55     insertStmt.close()
56     updateSmt.close()
57     conn.close()
58   }
59 }
60 点击并拖拽以移动

【4】输出结果展示
 

posted @ 2020-11-14 19:12  Java程序员进阶  阅读(2)  评论(0编辑  收藏  举报