我先说说我的业务需求, 我想要实时从mysql数据库中读取配置数据,我以前没接触这个技术之前是定时从数据库中获取数据,但是将数据间隔设置太小就会出现问题,所以达不到纯实时的效果.
下面开始介绍一下准备工作:
支持的数据库(下面是官方的建议:MySQL | Apache Flink CDC)
Connector | Database | Driver | |
mysql-cdc |
| JDBC Driver: 8.0.27 |
依赖
我这里用的是Maven仓库,官方目前最新的就是3.2.0,但是推荐使用稳定发行的版本,下面以2.3.0为列
<dependency> <groupId>org.apache.flink</groupId> <artifactId>flink-connector-mysql-cdc</artifactId> <version>2.3.0</version> </dependency>
下面是从mysql中读取数据的案例
startupOptions常用参数:
- StartupOptions.initial() (默认):在第一次启动时对受监视的数据库表执行初始快照,并继续读取最新的 binlog。(第一次读取全部数据,后面读取最新数据)
- StartupOptions.
earliest()
:跳过快照阶段,从可读取的最早 binlog 位点开始读取- StartupOptions.
latest()
:首次启动时,从不对受监视的数据库表执行快照, 连接器仅从 binlog 的结尾处开始读取,这意味着连接器只能读取在连接器启动之后的数据更改。- StartupOptions.
specificOffset("mysql-bin.00003",4L)
:跳过快照阶段,从指定的 binlog 位点开始读取。位点可通过 binlog 文件名和位置指定,或者在 GTID 在集群上启用时通过 GTID 集合指定。- StartupOptions.
timestamp(16666666666644L)
:跳过快照阶段,从指定的时间戳开始读取 binlog 事件
public static void getMySQLSource() throws Exception {
Configuration conf = new Configuration();
conf.setInteger("rest.port",10050);
StreamExecutionEnvironment env =
StreamExecutionEnvironment.createLocalEnvironment(conf);
Properties properties = new Properties();
properties.setProperty("userSSL","false");
properties.setProperty("allowPublickeyRetrieval","true");
String database = "pro";
String tableName = "books";
String username = "root";
String password = "123456";
MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
.hostname("127.0.0.1")
.port(3307)
.databaseList("pro") //设置监控的数据库,如果要监控全部数据库,将该值设为:".*"
.tableList(database+"."+tableName)//设置表名称,可以添加多个
.username(username) //该用户需要有执行CDC相关操作的权限
.password(password)
.deserializer(new JsonDebeziumDeserializationSchema())//将结果转为JSON字符串
.startupOptions(StartupOptions.initial())//第一次读取全部数据,后面读取最新数据
.jdbcProperties(properties)//设置一些连接参数
.build();
DataStreamSource<String> mysqlSource = env.fromSource(mySqlSource,
WatermarkStrategy.noWatermarks(), "mysql_source")
.setParallelism(1);
mysqlSource.print().setParallelism(1);
env.execute();
}
返回结果样例:
before : 执行删除或修改之前的数据
after : 现在的数据
source : 一些基础信息
op : 执行的操作 (c:添加 d:删除 u:修改)
{
- "before":null,
- "after":{
},
- "bookID":1,
- "title":"spark",
- "publisher":"授权人民邮电出版社出版",
- "publisherDate":20332,
- "ISBN":"978-7-115-40309-4",
- "edition":"第1版",
- "language":"中文",
- "genre":"大数据",
- "summarv":"spark能够收集,计算数据",
- "price":59.0,
- "stockQuantity":5,
- "location":"3-1-3",
- "status":"是"
- "source":{
},
- "version":"1.6.4.Final",
- "connector":"mysql",
- "name":"mysql_binlog_source",
- "ts_ms":0,
- "snapshot":"false",
- "db":"pro",
- "sequence":null,
- "table":"books",
- "server_id":0,
- "gtid":null,
- "file":"",
- "pos":0,
- "row":0,
- "thread":null,
- "query":null
- "op":"r",
- "ts_ms":1732851051565,
- "transaction":null
}