Flink FileSystem抽象类了解
Flink在集群启动的第一个操作就是初始化文件系统。Flink中的文件系统主要有两个用途,
第一:Flink实现容错,存储程序状态,恢复数据,主要通过FsDataOutputStream实例来实现。第二:保存链接状态,避免每次创建链接的资源消耗。
Flink的文件系统功能定义主要在org.apache.flink.core.fs.FileSystem中。Flink本身文件系统是插件式来实现,默认实现LocalFileSystem,同时通过插件方式通过SPI方式进行文件系统加载,如果plugin没有匹配成功的话,用HadoopFileSystem作为兜底方案。
Flink目前支撑的主流文件系统有:
hdfs: Hadoop Distributed File Systems3,s3n, ands3a: Amazon S3 file systemgcs: Google Cloud Storagemaprfs: The MapR distributed file system
都是通过配置FLINK_PLUGINS_DIR变量指定插件所在目录,通过SPI方式加载实现了org.apache.flink.core.fs.FileSystem且在对应jar文件中META-INF/services/ 目录下进行注册的类。
在org.apache.flink.core.fs.FileSystem只定义类简单通用的方法,下面是该抽象类中的主要内容:

大部分都是抽象方法,没有具体实现,重点看一下initialize方法,内容如下:
1 public static void initialize( 2 Configuration config, 3 PluginManager pluginManager) throws IllegalConfigurationException { 4 5 LOCK.lock(); 6 try { 7 // make sure file systems are re-instantiated after re-configuration 8 CACHE.clear(); 9 FS_FACTORIES.clear(); 10 11 Collection<Supplier<Iterator<FileSystemFactory>>> factorySuppliers = new ArrayList<>(2); 12 factorySuppliers.add(() -> ServiceLoader.load(FileSystemFactory.class).iterator()); 13 14 if (pluginManager != null) { 15 factorySuppliers.add(() -> 16 Iterators.transform(pluginManager.load(FileSystemFactory.class), PluginFileSystemFactory::of)); 17 } 18 19 final List<FileSystemFactory> fileSystemFactories = loadFileSystemFactories(factorySuppliers); 20 21 // configure all file system factories 22 for (FileSystemFactory factory : fileSystemFactories) { 23 factory.configure(config); 24 String scheme = factory.getScheme(); 25 26 FileSystemFactory fsf = ConnectionLimitingFactory.decorateIfLimited(factory, scheme, config); 27 FS_FACTORIES.put(scheme, fsf); 28 } 29 30 // configure the default (fallback) factory 31 FALLBACK_FACTORY.configure(config); 32 33 // also read the default file system scheme 34 final String stringifiedUri = config.getString(CoreOptions.DEFAULT_FILESYSTEM_SCHEME, null); 35 if (stringifiedUri == null) { 36 defaultScheme = null; 37 } 38 else { 39 try { 40 defaultScheme = new URI(stringifiedUri); 41 } 42 catch (URISyntaxException e) { 43 throw new IllegalConfigurationException("The default file system scheme ('" + 44 CoreOptions.DEFAULT_FILESYSTEM_SCHEME + "') is invalid: " + stringifiedUri, e); 45 } 46 } 47 } 48 finally { 49 LOCK.unlock(); 50 } 51 }
12行,通过SPI方式加载FileSystemFactory。
14-17行,通过配置信息,主要是扫描FLINK_PLUGINS_DIR变量指定的plugin目录,通过SPI方式进行文件系统类型的加载。
19行通过loadFileSystemFactories方法加载文件系统中,会总是把LocalFileSystemFactory加进去。
31行FALLBACK_FACTORY.configure(config);作为兜底方案,会默认对HadoopFileSystem进行加载。如果运行环境中没有Hadoop相关的代码实现,会throw一些异常信息,但是有其他文件系统的情况下,不影响程序运行。
在FileSystem抽象类中还有两个方法值得研究一下, initOutPathLocalFS、initOutPathDistFS通过WriteMode的判定,对输出目录的具体操作。但是具体的delete,create,open等方法是调用不同文件系统格子的实现方式。

浙公网安备 33010602011771号