Apache Flink 零基础入门(十四)Flink 分布式缓存

Apache Flink 提供了一个分布式缓存,类似于Hadoop,用户可以并行获取数据。

通过注册一个文件或者文件夹到本地或者远程HDFS等,在getExecutionEnvironment中指定一个名字就可以。当应用程序执行时,Flink会自动拷贝这个文件或者文件夹到所有worker进程中。用户的Function通过指定的名字可以查找这个文件或者文件夹中的内容。

Scala

def main(args: Array[String]): Unit = {
    val environment = ExecutionEnvironment.getExecutionEnvironment

    val filePath = "E:/test/hello.txt"
    // step1: 注册一个本地文件
    environment.registerCachedFile(filePath, "pk-scala-dc")
    val data = environment.fromElements("hadoop", "spark", "flink", "pyspark")
    val info=data.map(new RichMapFunction[String, String] {

      //step2: 在open方法中获取到分布式缓存的内容即可
      override def open(parameters: Configuration): Unit = {
        val dcfile = getRuntimeContext.getDistributedCache.getFile("pk-scala-dc")
        val lines = FileUtils.readLines(dcfile)
        import scala.collection.JavaConverters._
        for(ele <- lines.asScala){
          println(ele)
        }
      }

      override def map(value: String): String = {
        value
      }
    })
    info.writeAsText("E:/test3", WriteMode.OVERWRITE).setParallelism(4)
    environment.execute("DistributedCacheApp")
  }

Java

public class JavaDistributedCachedApp {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment executionEnvironment = ExecutionEnvironment.getExecutionEnvironment();
        executionEnvironment.registerCachedFile("E:/test/hello.txt", "pk-java-dc");
        DataSource<String> data1 = executionEnvironment.fromElements("hadoop", "spark", "flink", "pyspark");
        data1.map(new RichMapFunction<String, String>() {
            List<String> list = new ArrayList<>();

            @Override
            public void open(Configuration parameters) throws Exception {
                File file = getRuntimeContext().getDistributedCache().getFile("pk-java-dc");
                List<String> lines = FileUtils.readLines(file);
                for (String line : lines) {
                    list.add(line);
                    System.out.println(list);
                }
            }

            @Override
            public String map(String value) throws Exception {
                return value;
            }
        }).print();

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值