繁体   English   中英

Apache Spark并发程序示例

[英]Apache Spark concurrent program example

我希望以下简单的hello world程序在Apache Spark中并行执行100次。

  public class SimpleHelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
  }

因此,在并行执行后,它应该打印“ Hello World” 100次。

如何在独立的Apache Spark中做到这一点?

取决于您真正想要的是:

  1. Spark-Driver中的多线程:例如
import scala.collection.parallel._
    import scala.concurrent.forkjoin._
    val pool = (0 to 100).par
    // ThreadPool with 100 concurrent Threads
    pool.tasksupport = new ForkJoinTaskSupport(new ForkJoinPool(100))
    pool.foreach(i => {
        println("Hello World")
    })
  1. 每个Spark-Executor任务的“多线程”:例如
// create 100 partitions
    var df = sc.parallelize(1 to 100, 100).toDF()
    // print "hello world" per each partition
    df.foreachPartition(_ => println("Hello World"))

这将在Spark 2.x中的Scala中实现您想要的功能:

sparkSession.range(100)
.foreach(_ => println("Hello World"))

但是您不会在驱动程序上看到打印的行,因为它们是在工作程序节点上执行的。

您好,如果您想在这种情况下运行火花机。

对于Spark作业,您需要首先启动RDD。 然后使用Spark动作或转换函数进行数据计算。 另外,自动触发它并行运行。

   public class hello world {

        public static void main(String[] args) throws Exception {

                try (JavaSparkContext sc = setupSparkContext()) {

            JavaRDD<String> helloworldRDD = sc.textFile("//your hellworld file");
                helloworldRDD.map(x->{
                    for (int i=0;i<100;i++){

                        System.out.println(x);

                    }
                    return x;

                }).collect();
        }
        }

        private static JavaSparkContext setupSparkContext() {

            SparkConf sc = new SparkConf();

            return App.getSparkContext("helloworld", sc);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM