要使用Flink SQL讀取Kafka數(shù)據(jù),需要按照以下步驟進(jìn)行操作:
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-connector-kafka_2.12</artifactId>
<version>${flink.version}</version>
</dependency>
確保${flink.version}
是Flink的版本號。
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
String createTableSql = "CREATE TABLE kafka_table (\n" +
" key STRING,\n" +
" value STRING\n" +
") WITH (\n" +
" 'connector' = 'kafka',\n" +
" 'topic' = 'your_topic',\n" +
" 'properties.bootstrap.servers' = 'your_bootstrap_servers',\n" +
" 'properties.group.id' = 'your_group_id',\n" +
" 'format' = 'json',\n" +
" 'scan.startup.mode' = 'earliest-offset'\n" +
")";
tEnv.executeSql(createTableSql);
在上述代碼中,'topic'
和'properties.bootstrap.servers'
需要替換為你的Kafka主題和啟動(dòng)服務(wù)器的地址。'properties.group.id'
是Flink消費(fèi)者組的唯一標(biāo)識(shí)符。
另外,'format'
參數(shù)指定了數(shù)據(jù)格式,可以根據(jù)實(shí)際情況將其設(shè)置為適當(dāng)?shù)闹怠?/p>
String querySql = "SELECT * FROM kafka_table";
Table result = tEnv.sqlQuery(querySql);
DataStream<Row> resultStream = tEnv.toAppendStream(result, Row.class);
現(xiàn)在,你可以對resultStream
進(jìn)行進(jìn)一步處理,如打印或?qū)懭氲狡渌到y(tǒng)中。
最后,記得調(diào)用env.execute()
啟動(dòng)Flink作業(yè)。