博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Flink分布式缓存
阅读量:2055 次
发布时间:2019-04-28

本文共 1629 字,大约阅读时间需要 5 分钟。

官方参考文档地址:https://ci.apache.org/projects/flink/flink-docs-release-1.2/dev/batch/index.html#distributed-cache

Flink提供了一个类似于Hadoop的分布式缓存,让并行运行实例的函数可以在本地访问。这个功能可以被使用来分享外部静态的数据,例如:机器学习的逻辑回归模型等!

缓存的使用流程:

 使用ExecutionEnvironment实例对本地的或者远程的文件(例如:HDFS上的文件),为缓存文件指定一个名字注册该缓存文件!当程序执行时候,Flink会自动将复制文件或者目录到所有worker节点的本地文件系统中,函数可以根据名字去该节点的本地文件系统中检索该文件!

接下来直接上代码:

package com.daxinimport java.io.{FileReader, BufferedReader}import org.apache.flink.api.common.functions.RichMapFunctionimport org.apache.flink.api.scala.ExecutionEnvironmentimport org.apache.flink.api.scala._import org.apache.flink.configuration.Configurationimport scala.collection.mutable.HashMap/**  *  * Created by Daxin on 2017/4/18.  *  */object DistributedCache {  def main(args: Array[String]) {    val env = ExecutionEnvironment.getExecutionEnvironment    //本地IDE运行,缓存的是本地文件,缓存文件名字为cahce    env.registerCachedFile("file:///C://logs//flink", "cache")    val data = env.fromElements("111", "222", "333")    val result = data.map(new RichMapFunction[String, String] {      val map = HashMap[String, String]()      override def open(parameters: Configuration): Unit = {        val file = getRuntimeContext.getDistributedCache.getFile("cache")//获取缓存文件        //读取缓存文件内容到HashMap中,这个也可以使用广播实现        val br = new BufferedReader(new FileReader(file))        var line = br.readLine()        while (line != null) {          map.put(line, line + "" + line)          line = br.readLine()        }      }      override def map(value: String): String = {        map.getOrElse(value, "default") //返回该value在map中的value值,如果不存在key为value的返回默认default      }    })    result.print() //执行作业  }}

转载地址:http://ffjlf.baihongyu.com/

你可能感兴趣的文章
leetcode 热题 Hot 100-3. 合并两个有序链表
查看>>
leetcode 热题 Hot 100-4. 对称二叉树
查看>>
Leetcode C++《热题 Hot 100-12》226.翻转二叉树
查看>>
Leetcode C++《热题 Hot 100-13》234.回文链表
查看>>
Leetcode C++《热题 Hot 100-14》283.移动零
查看>>
Leetcode C++《热题 Hot 100-15》437.路径总和III
查看>>
Leetcode C++《热题 Hot 100-16》448.找到所有数组中消失的数字
查看>>
Leetcode C++《热题 Hot 100-17》461.汉明距离
查看>>
Leetcode C++《热题 Hot 100-18》538.把二叉搜索树转换为累加树
查看>>
Leetcode C++《热题 Hot 100-19》543.二叉树的直径
查看>>
Leetcode C++《热题 Hot 100-21》581.最短无序连续子数组
查看>>
Leetcode C++《热题 Hot 100-22》2.两数相加
查看>>
Leetcode C++《热题 Hot 100-23》3.无重复字符的最长子串
查看>>
Leetcode C++《热题 Hot 100-24》5.最长回文子串
查看>>
Leetcode C++《热题 Hot 100-26》15.三数之和
查看>>
Leetcode C++《热题 Hot 100-27》17.电话号码的字母组合
查看>>
Leetcode C++《热题 Hot 100-28》19.删除链表的倒数第N个节点
查看>>
Leetcode C++《热题 Hot 100-29》22.括号生成
查看>>
Leetcode C++《热题 Hot 100-30》31.下一个排列
查看>>
Leetcode C++《热题 Hot 100-40》64.最小路径和
查看>>