mysql和flink_11-flink读写MySQL

本文详细介绍了Flink如何读写MySQL数据库,包括通过JDBC方式定义MySQLDataSource类进行读操作,自定义DataSource方式实现数据读取,以及通过JDBC和自定义Sink方式实现数据写入。对比了JDBC与自定义方式的优缺点。
摘要由CSDN通过智能技术生成

一、读MySQL

1、通过JDBC方式定义MySQLDataSource类

1.1首先加入JDBC依赖

1.2定义JDBCInputFormat

1.3获取Row类型的DataStreamSource

1.4转化DataStream为DataStream

public class MysqlDataSource {

private static final Logger log = LoggerFactory.getLogger(MySQLDataSource.class);

public static DataStream readFromDb(StreamExecutionEnvironment streamExecutionEnvironment) throws Exception {

//final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

//1.定义field 类型

TypeInformation[] fieldTypes = new TypeInformation[]{BasicTypeInfo.INT_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.INT_TYPE_INFO};

//2.定义field name

String[] fieldNames = new String[]{"id", "name", "password", "age"};

//3.定义Row类型

RowTypeInfo rowTypeInfo = new RowTypeInfo(fieldTypes, fieldNames);

String jdbcUrl = parameterTool.get(PropertiesConstants.MYSQL_JDBC_URL);

log.info(jdbcUrl);

//4.定义JDBCInputFormat

JDBCInputFormat jdbcInputFormat = JDBCInputFormat

.buildJDBCInputFormat()

.setDrivername("com.mysql.jdbc.Driver")

.setDBUrl(jdbcUrl)

.setUsername(parameterTool.get(PropertiesConstants.MYSQL_USERNAME))

.setPassword(parameterTool.get(PropertiesConstants.MYSQL_PASSWORD))

.setQuery("select id, name, password, age from student")

.setRowTypeInfo(rowTypeInfo)

.finish();

//5.以JDBCInputFormat形式读取MySQL DB数据

DataStreamSource dataStreamSourceRow = streamExecutionEnvironment.createInput(jdbcInputFormat);

//阶段性验证可以正确读取

dataStreamSourceRow.print();

//6.将Row类型Stream转化为Entity类型

DataStream dataStream = dataStreamSourceRow.map(new RichMapFunction() {

@Override

public Student map(Row value) throws Exception {

Student s = new Student();

s.setId((Integer) value.getField(0));

s.setName((String) value.getField(1));

<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值