flink深入研究(08) flink的StreamExecutionEnvironment.execute()函数调用过程02

Flink Closure Cleaner解析

上一篇我们讲到了ClosureCleaner的clean函数,这一篇我们继续往下分析,在clean函数中又调用了另外一个clean函数clean(func, level, checkSerializable, Collections.newSetFromMap(new IdentityHashMap<>()));代码如下:

private static void clean(Object func, ExecutionConfig.ClosureCleanerLevel level, boolean checkSerializable, Set<Object> visited) {
		if (func == null) {
			return;
		}
        //将func保存起来
		if (!visited.add(func)) {
			return;
		}
        //获取Object的Class对象
		final Class<?> cls = func.getClass();
        /*判断是否为基础类型还是包装类型,所谓基础类型就是int、float、long等这种非类对象类型
          包装类型就是基础类型对应的Integer、Float、Long等类对象类型。
          由于基础类型或者非基础类型
        */
		if (ClassUtils.isPrimitiveOrWrapper(cls)) {
			return;
		}
        //通过反射判断cls中是否有序列化函数writeReplace、writeObject,关于这两个函数的使用可以自己搜索一下,这里不详解
		if (usesCustomSerialization(cls)) {
			return;
		}

		// First find the field name of the "this$0" field, this can
		// be "this$x" depending on the nesting
		boolean closureAccessed = false;
        //开始遍历cls中的所有成员变量
		for (Field f: cls.getDeclaredFields()) {
            //这部分代码我们下面详细讲解一下
			if (f.getName().startsWith("this$")) {
				// found a closure referencing field - now try to clean
				closureAccessed |= cleanThis0(func, cls, f.getName());
			} else {
				Object fieldObject;
				try {
                    //将该变量设置为可访问
					f.setAccessible
若要把使用 Flink 读取 PostgreSQL 数据的 Java 程序进行改写,使其能将读取到的数据写入文件,可按以下步骤操作: 1. **读取 PostgreSQL 数据**:使用 Flink 的 JDBC 连接器从 PostgreSQL 读取数据。 2. **将数据写入文件**:使用 Flink 的 FileSink 将数据写入文件。 以下是示例代码: ```java import org.apache.flink.api.common.serialization.SimpleStringSchema; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.connector.file.sink.FileSink; import org.apache.flink.core.fs.Path; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.sink.filesystem.OutputFileConfig; import org.apache.flink.streaming.api.functions.sink.filesystem.StreamingFileSink; import org.apache.flink.streaming.api.functions.sink.filesystem.bucketassigners.DateTimeBucketAssigner; import org.apache.flink.streaming.api.functions.sink.filesystem.rollingpolicies.DefaultRollingPolicy; import org.apache.flink.streaming.connectors.jdbc.JdbcConnectionOptions; import org.apache.flink.streaming.connectors.jdbc.JdbcExecutionOptions; import org.apache.flink.streaming.connectors.jdbc.JdbcSource; import org.apache.flink.streaming.connectors.jdbc.JdbcStatementBuilder; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.concurrent.TimeUnit; public class FlinkPostgreSQLToFile { public static void main(String[] args) throws Exception { // 创建执行环境 StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); // 配置 PostgreSQL 连接 JdbcConnectionOptions connectionOptions = new JdbcConnectionOptions.JdbcConnectionOptionsBuilder() .withUrl("jdbc:postgresql://localhost:5432/your_database") .withDriverName("org.postgresql.Driver") .withUsername("your_username") .withPassword("your_password") .build(); // 从 PostgreSQL 读取数据 DataStream<Tuple2<Integer, String>> stream = JdbcSource.<Tuple2<Integer, String>>source( "SELECT id, name FROM your_table", new JdbcStatementBuilder<Tuple2<Integer, String>>() { @Override public void accept(PreparedStatement preparedStatement, Tuple2<Integer, String> t) throws SQLException { // 这里不需要做任何事情,因为只是查询 } }, new org.apache.flink.streaming.connectors.jdbc.JdbcDeserializationSchema<Tuple2<Integer, String>>() { @Override public Tuple2<Integer, String> deserialize(java.sql.ResultSet resultSet) throws SQLException { return new Tuple2<>(resultSet.getInt(1), resultSet.getString(2)); } @Override public org.apache.flink.api.common.typeinfo.TypeInformation<Tuple2<Integer, String>> getProducedType() { return org.apache.flink.api.java.typeutils.TupleTypeInfo.getBasicTupleTypeInfo( org.apache.flink.api.common.typeinfo.BasicTypeInfo.INT_TYPE_INFO, org.apache.flink.api.common.typeinfo.BasicTypeInfo.STRING_TYPE_INFO ); } }, connectionOptions ); // 配置文件输出 OutputFileConfig config = OutputFileConfig .builder() .withPartPrefix("prefix") .withPartSuffix(".ext") .build(); FileSink<String> sink = FileSink .forRowFormat(new Path("file:///path/to/output"), new SimpleStringSchema()) .withBucketAssigner(new DateTimeBucketAssigner<>("yyyy-MM-dd--HH")) .withRollingPolicy( DefaultRollingPolicy.builder() .withRolloverInterval(TimeUnit.MINUTES.toMillis(15)) .withInactivityInterval(TimeUnit.MINUTES.toMillis(5)) .withMaxPartSize(1024 * 1024 * 1024) .build()) .withOutputFileConfig(config) .build(); // 将数据转换为字符串并写入文件 stream.map(t -> t.f0 + "," + t.f1) .sinkTo(sink); // 执行作业 env.execute("Flink PostgreSQL to File"); } } ``` ### 代码说明: 1. **创建执行环境**:使用 `StreamExecutionEnvironment.getExecutionEnvironment()` 创建 Flink 执行环境。 2. **配置 PostgreSQL 连接**:使用 `JdbcConnectionOptions` 配置 PostgreSQL 连接信息。 3. **从 PostgreSQL 读取数据**:使用 `JdbcSource` 从 PostgreSQL 读取数据。 4. **配置文件输出**:使用 `FileSink` 配置文件输出,包括文件路径、文件格式、分桶策略和滚动策略。 5. **将数据转换为字符串并写入文件**:使用 `map` 函数将数据转换为字符串,然后使用 `sinkTo` 方法将数据写入文件。 6. **执行作业**:调用 `env.execute` 方法执行 Flink 作业。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值