gpt4 book ai didi

java - Spark 程序中发布广播变量

转载 作者:行者123 更新时间:2023-11-30 03:10:40 24 4
gpt4 key购买 nike

在spark-java程序中,我需要读取一个配置文件并填充一个HashMap,我需要将其发布为广播变量,以便它可以在所有数据节点上使用。

我需要在将在 datanodes 中运行的 CustomInputFormat 类中获取此广播变量的值。由于广播变量是在我的驱动程序中声明的,因此如何在 CustomInputFormat 类中指定从特定广播变量获取值?

我添加了一些代码来解释它:

在这种情况下,我在驱动程序本身中使用它,即变量在同一个类中使用:这里我可以使用 Broadcat.value() 方法

> final Broadcast<String[]> signPrefixes =
> sc.broadcast(loadCallSignTable());
> JavaPairRDD<String, Integer> countryContactCounts = contactCounts.mapToPair(
> new PairFunction<Tuple2<String, Integer>, String, Integer> (){
> public Tuple2<String, Integer> call(Tuple2<String, Integer> callSignCount) {
> String sign = callSignCount._1();
> String country = lookupCountry(sign, signPrefixes.value());
> return new Tuple2(country, callSignCount._2());
> }}).reduceByKey(new SumInts());

在场景 2 中,我将在自定义输入格式类中使用广播变量:

驱动程序:

> final JavaSparkContext sc=    new
> JavaSparkContext(sConf.setAppName("ParserSpark").setMaster("yarn-cluster"));
> Broadcast<int[]> broadcastVar = sc.broadcast(new int[] {1, 2, 3});
>
> JavaPairRDD<NullWritable, ArrayList<Record>> baseRDD =
> sc.newAPIHadoopFile(args[2], InputFormat.class, NullWritable.class,
> ArrayList.class, conf);

InputFormat.class

> public class InputFormat extends  FileInputFormat {
>
> @Override public RecordReader<NullWritable, ArrayList<Record>>
> createRecordReader(InputSplit split, TaskAttemptContext context)
> throws IOException, InterruptedException{
> //I want to get the Broadcast Variable Here -- How will I do it
>
> RecordReader reader = new RecordReader(); reader.initialize(split, context); return reader; } @Override
> protected boolean isSplitable(JobContext context, Path file) {
> return false; } }

最佳答案

我最近遇到了这个问题。实际上,结果相当简单(几个小时后,然后......哈哈!)

创建一个新的配置,设置您的变量,并将其传递给 newAPIHadoopFile 的稍微不同的实现功能。

来自驱动程序(此处使用 Scala):

val myConf = new Configuration();
myConf.set("var1", v1)
myConf.set("var2", v2)
myConf.set("var3", v3)

val yourFile = sc.newAPIHadoopFile("yourFilePath", classOf[MyFileInputFormat],classOf[org.apache.hadoop.io.Text], classOf[org.apache.hadoop.io.DoubleWritable],myConf)

从你的InputFormat或InputReader..或者任何你有上下文的地方(这次是Java)

context.getConfiguration().get("var1");

或者也许

job.getConfiguration().get("var2");

关于java - Spark 程序中发布广播变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33698882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com