Flink Distributed Cache 分布式緩衝

來源:互聯網
上載者:User

Flink提供了一個分布式緩衝,類似於hadoop,可以使使用者在並行函數中很方便的讀取本地檔案。此功能可用於共用檔案,包含靜態外部資料,例如字典或者machine-learned迴歸模型。

此緩衝的工作機制如下:程式註冊一個檔案或者目錄(本地或者遠程檔案系統,例如hdfs或者s3),通過ExecutionEnvironment註冊快取檔案並為它起一個名稱。當程式執行,Flink自動將檔案或者目錄複寫到所有worker節點的本地檔案系統。使用者函數可以尋找檔案或者目錄通過這個指定的名稱,然後從worker節點的本地檔案系統訪問它。

使用分布式緩衝 如下樣本:

java代碼:

在ExecutionEnvironment中註冊檔案或者目錄

ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();// 從hdfs註冊一個檔案env.registerCachedFile("hdfs:///path/to/your/file", "hdfsFile")// 註冊一個本地可執行檔指令檔env.registerCachedFile("file:///path/to/exec/file", "localExecFile", true)// 定義程式碼 並且執行...DataSet<String> input = ...DataSet<Integer> result = input.map(new MyMapper());...env.execute();

在使用者函數中訪問快取檔案或者目錄(這裡是一個map函數)。這個函數必須繼承RichFunction,因為它需要使用RuntimeContext讀取資料

// 繼承RichFunction 為了擷取RuntimeContextpublic final class MyMapper extends RichMapFunction<String, Integer> {    @Override    public void open(Configuration config) {      // 通過RuntimeContext 和 DistributedCache訪問快取檔案      File myFile = getRuntimeContext().getDistributedCache().getFile("hdfsFile");      // 讀取檔案(或者本地目錄)      ...    }    @Override    public Integer map(String value) throws Exception {      // 使用快取檔案的內容做一些處理      ...    }}



scala代碼:

在ExecutionEnvironment中註冊檔案或者目錄

val env = ExecutionEnvironment.getExecutionEnvironment// 從hdfs註冊一個檔案env.registerCachedFile("hdfs:///path/to/your/file", "hdfsFile")// 註冊一個本地可執行檔指令檔env.registerCachedFile("file:///path/to/exec/file", "localExecFile", true)// 定義程式碼 並且執行...val input: DataSet[String] = ...val result: DataSet[Integer] = input.map(new MyMapper())...env.execute()

在使用者函數中訪問快取檔案或者目錄(這裡是一個map函數)。這個函數必須繼承RichFunction,因為它需要使用RuntimeContext讀取資料

// 繼承RichFunction 為了擷取RuntimeContextclass MyMapper extends RichMapFunction[String, Int] {  override def open(config: Configuration): Unit = {    // 通過RuntimeContext 和 DistributedCache訪問快取檔案    val myFile: File = getRuntimeContext.getDistributedCache.getFile("hdfsFile")    // 讀取檔案(或者本地目錄)    ...  }  override def map(value: String): Int = {    // 使用快取檔案的內容做一些處理    ...  }}

擷取更多大資料資料,視頻以及技術交流請加群:

QQ群號1:295505811(已滿)

QQ群號2:54902210

QQ群號3:555684318






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.