flink读取kafka数据,并将偏移量保存到Mysql
时间: 2023-11-19 17:04:31 浏览: 166
Flink实时读取Kafka数据批量聚合(定时按数量)写入Mysql.rar
5星 · 资源好评率100%
可以通过Flink的Kafka Consumer实现从Kafka中读取数据,并通过Flink的JDBC Output Format将偏移量保存到MySQL中。以下是一个简单的示例代码:
```
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.AssignerWithPunctuatedWatermarks;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.flink.streaming.connectors.kafka.KafkaSink;
import org.apache.flink.streaming.util.serialization.KeyedSerializationSchemaWrapper;
import org.apache.flink.types.Row;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
public class FlinkKafkaToMysql {
public static void main(String[] args) throws Exception {
// 获取参数
final ParameterTool parameterTool = ParameterTool.fromArgs(args);
// 设置执行环境
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(5000, CheckpointingMode.EXACTLY_ONCE);
// 设置Kafka Consumer
Properties properties = new Properties();
properties.setProperty("bootstrap.servers", parameterTool.get("bootstrap.servers"));
properties.setProperty("group.id", parameterTool.get("group.id"));
FlinkKafkaConsumer<String> consumer = new FlinkKafkaConsumer<>(parameterTool.get("input.topic"), new SimpleStringSchema(), properties);
// 设置Kafka Producer
FlinkKafkaProducer<Row> producer = new FlinkKafkaProducer<>(parameterTool.get("output.topic"), new KafkaSerializationSchema<Row>() {
@Override
public ProducerRecord<byte[], byte[]> serialize(Row element, @Nullable Long timestamp) {
return new ProducerRecord<>(parameterTool.get("output.topic"), element.toString().getBytes(StandardCharsets.UTF_8));
}
}, properties, FlinkKafkaProducer.Semantic.EXACTLY_ONCE);
// 设置JDBC Output Format
JDBCOutputFormat jdbcOutputFormat = JDBCOutputFormat.buildJDBCOutputFormat()
.setDrivername(parameterTool.get("jdbc.driver"))
.setDBUrl(parameterTool.get("jdbc.url"))
.setUsername(parameterTool.get("jdbc.username"))
.setPassword(parameterTool.get("jdbc.password"))
.setQuery("INSERT INTO " + parameterTool.get("mysql.table") + " (topic, partition, offset) VALUES (?, ?, ?)")
.setSqlTypes(new int[] {java.sql.Types.VARCHAR, java.sql.Types.INTEGER, java.sql.Types.BIGINT})
.finish();
// 读取Kafka数据并保存偏移量到MySQL
DataStream<String> inputStream = env.addSource(consumer);
inputStream.map(new MapFunction<String, Row>() {
@Override
public Row map(String value) throws Exception {
String[] parts = value.split(",");
return Row.of(parts[0], Integer.parseInt(parts[1]), Long.parseLong(parts[2]));
}
}).addSink(new SinkFunction<Row>() {
@Override
public void invoke(Row value, Context context) throws Exception {
jdbcOutputFormat.writeRecord(value);
}
});
// 执行任务
env.execute("Flink Kafka to MySQL");
}
}
```
在上述代码中,我们首先通过`ParameterTool`获取传入的参数,然后设置Flink的执行环境和Kafka Consumer。接着,我们创建了一个`JDBCOutputFormat`对象,用于将数据保存到MySQL中。最后,我们通过`DataStream.map()`操作将Kafka中读取的数据转换成`Row`对象,并通过`SinkFunction`将偏移量保存到MySQL中。
需要注意的是,在保存数据到MySQL时,我们使用了`JDBCOutputFormat`的`writeRecord()`方法,该方法会自动打开和关闭数据库连接。因此,我们不需要手动管理数据库连接。
阅读全文