How to run a Spark Java program

前端 未结 4 818
一个人的身影
一个人的身影 2021-01-29 21:01

I have written a Java program for Spark. But how to run and compile it from Unix command line. Do I have to include any jar while compiling for running

相关标签:
4条回答
  • 2021-01-29 21:40

    This answer is for Spark 2.3.If you want to test your Spark application locally, ie without the pre-requisite of a Hadoop cluster, and even without having to start any of the standalone Spark services, you could do this:

    JavaSparkContext jsc = new JavaSparkContext(new SparkConf().setAppName("Simple App"));
    

    And then, to run your application locally:

    $SPARK_HOME/bin/spark-submit --class SimpleApp --master local target/scala-2.10/simple-project_2.10-1.0.jar
    

    For this to work , you just need to extract the Spark tar file into $SPARK_HOME, and set $SPARK_HOME into the Spark user's .profile

    0 讨论(0)
  • 2021-01-29 21:42

    Combining steps from official Quick Start Guide and Launching Spark on YARN we get:

    We’ll create a very simple Spark application, SimpleApp.java:

    /*** SimpleApp.java ***/
    import org.apache.spark.api.java.*;
    import org.apache.spark.api.java.function.Function;
    
    public class SimpleApp {
      public static void main(String[] args) {
        String logFile = "$YOUR_SPARK_HOME/README.md"; // Should be some file on your system
        JavaSparkContext sc = new JavaSparkContext("local", "Simple App",
          "$YOUR_SPARK_HOME", new String[]{"target/simple-project-1.0.jar"});
        JavaRDD<String> logData = sc.textFile(logFile).cache();
    
        long numAs = logData.filter(new Function<String, Boolean>() {
          public Boolean call(String s) { return s.contains("a"); }
        }).count();
    
        long numBs = logData.filter(new Function<String, Boolean>() {
          public Boolean call(String s) { return s.contains("b"); }
        }).count();
    
        System.out.println("Lines with a: " + numAs + ", lines with b: " + numBs);
      }
    }
    

    This program just counts the number of lines containing ‘a’ and the number containing ‘b’ in a text file. Note that you’ll need to replace $YOUR_SPARK_HOME with the location where Spark is installed. As with the Scala example, we initialize a SparkContext, though we use the special JavaSparkContext class to get a Java-friendly one. We also create RDDs (represented by JavaRDD) and run transformations on them. Finally, we pass functions to Spark by creating classes that extend spark.api.java.function.Function. The Java programming guide describes these differences in more detail.

    To build the program, we also write a Maven pom.xml file that lists Spark as a dependency. Note that Spark artifacts are tagged with a Scala version.

    <project>
      <groupId>edu.berkeley</groupId>
      <artifactId>simple-project</artifactId>
      <modelVersion>4.0.0</modelVersion>
      <name>Simple Project</name>
      <packaging>jar</packaging>
      <version>1.0</version>
      <repositories>
        <repository>
          <id>Akka repository</id>
          <url>http://repo.akka.io/releases</url>
        </repository>
      </repositories>
      <dependencies>
        <dependency> <!-- Spark dependency -->
          <groupId>org.apache.spark</groupId>
          <artifactId>spark-core_2.10</artifactId>
          <version>0.9.0-incubating</version>
        </dependency>
      </dependencies>
    </project>
    

    If you also wish to read data from Hadoop’s HDFS, you will also need to add a dependency on hadoop-client for your version of HDFS:

    <dependency>
      <groupId>org.apache.hadoop</groupId>
      <artifactId>hadoop-client</artifactId>
      <version>...</version>
    </dependency>
    

    We lay out these files according to the canonical Maven directory structure:

    $ find .
    ./pom.xml
    ./src
    ./src/main
    ./src/main/java
    ./src/main/java/SimpleApp.java
    

    Now, we can execute the application using Maven:

    $ mvn package
    $ mvn exec:java -Dexec.mainClass="SimpleApp"
    ...
    Lines with a: 46, Lines with b: 23
    

    And then follow the steps from Launching Spark on YARN:

    Building a YARN-Enabled Assembly JAR

    We need a consolidated Spark JAR (which bundles all the required dependencies) to run Spark jobs on a YARN cluster. This can be built by setting the Hadoop version and SPARK_YARN environment variable, as follows:

    SPARK_HADOOP_VERSION=2.0.5-alpha SPARK_YARN=true sbt/sbt assembly
    

    The assembled JAR will be something like this: ./assembly/target/scala-2.10/spark-assembly_0.9.0-incubating-hadoop2.0.5.jar.

    The build process now also supports new YARN versions (2.2.x). See below.

    Preparations

    • Building a YARN-enabled assembly (see above).
    • The assembled jar can be installed into HDFS or used locally.
    • Your application code must be packaged into a separate JAR file.

    If you want to test out the YARN deployment mode, you can use the current Spark examples. A spark-examples_2.10-0.9.0-incubating file can be generated by running:

    sbt/sbt assembly 
    

    NOTE: since the documentation you’re reading is for Spark version 0.9.0-incubating, we are assuming here that you have downloaded Spark 0.9.0-incubating or checked it out of source control. If you are using a different version of Spark, the version numbers in the jar generated by the sbt package command will obviously be different.

    Configuration

    Most of the configs are the same for Spark on YARN as other deploys. See the Configuration page for more information on those. These are configs that are specific to SPARK on YARN.

    Environment variables:

    • SPARK_YARN_USER_ENV, to add environment variables to the Spark processes launched on YARN. This can be a comma separated list of environment variables, e.g.
    SPARK_YARN_USER_ENV="JAVA_HOME=/jdk64,FOO=bar"
    

    System Properties:

    • spark.yarn.applicationMaster.waitTries, property to set the number of times the ApplicationMaster waits for the the spark master and then also the number of tries it waits for the Spark Context to be intialized. Default is 10.
    • spark.yarn.submit.file.replication, the HDFS replication level for the files uploaded into HDFS for the application. These include things like the spark jar, the app jar, and any distributed cache files/archives.
    • spark.yarn.preserve.staging.files, set to true to preserve the staged files(spark jar, app jar, distributed cache files) at the end of the job rather then delete them.
    • spark.yarn.scheduler.heartbeat.interval-ms, the interval in ms in which the Spark application master heartbeats into the YARN ResourceManager. Default is 5 seconds.
    • spark.yarn.max.worker.failures, the maximum number of worker failures before failing the application. Default is the number of workers requested times 2 with minimum of 3.

    Launching Spark on YARN

    Ensure that HADOOP_CONF_DIR or YARN_CONF_DIR points to the directory which contains the (client side) configuration files for the hadoop cluster. This would be used to connect to the cluster, write to the dfs and submit jobs to the resource manager.

    There are two scheduler mode that can be used to launch spark application on YARN.

    Launch spark application by YARN Client with yarn-standalone mode.

    The command to launch the YARN Client is as follows:

    SPARK_JAR=<SPARK_ASSEMBLY_JAR_FILE> ./bin/spark-class org.apache.spark.deploy.yarn.Client \
      --jar <YOUR_APP_JAR_FILE> \
      --class <APP_MAIN_CLASS> \
      --args <APP_MAIN_ARGUMENTS> \
      --num-workers <NUMBER_OF_WORKER_MACHINES> \
      --master-class <ApplicationMaster_CLASS>
      --master-memory <MEMORY_FOR_MASTER> \
      --worker-memory <MEMORY_PER_WORKER> \
      --worker-cores <CORES_PER_WORKER> \
      --name <application_name> \
      --queue <queue_name> \
      --addJars <any_local_files_used_in_SparkContext.addJar> \
      --files <files_for_distributed_cache> \
      --archives <archives_for_distributed_cache>
    

    For example:

    # Build the Spark assembly JAR and the Spark examples JAR
    $ SPARK_HADOOP_VERSION=2.0.5-alpha SPARK_YARN=true sbt/sbt assembly
    
    # Configure logging
    $ cp conf/log4j.properties.template conf/log4j.properties
    
    # Submit Spark's ApplicationMaster to YARN's ResourceManager, and instruct Spark to run the SparkPi example
    $ SPARK_JAR=./assembly/target/scala-2.10/spark-assembly-0.9.0-incubating-hadoop2.0.5-alpha.jar \
        ./bin/spark-class org.apache.spark.deploy.yarn.Client \
          --jar examples/target/scala-2.10/spark-examples-assembly-0.9.0-incubating.jar \
          --class org.apache.spark.examples.SparkPi \
          --args yarn-standalone \
          --num-workers 3 \
          --master-memory 4g \
          --worker-memory 2g \
          --worker-cores 1
    
    # Examine the output (replace $YARN_APP_ID in the following with the "application identifier" output by the previous command)
    # (Note: YARN_APP_LOGS_DIR is usually /tmp/logs or $HADOOP_HOME/logs/userlogs depending on the Hadoop version.)
    $ cat $YARN_APP_LOGS_DIR/$YARN_APP_ID/container*_000001/stdout
    Pi is roughly 3.13794
    

    The above starts a YARN Client programs which start the default Application Master. Then SparkPi will be run as a child thread of Application Master, YARN Client will periodically polls the Application Master for status updates and displays them in the console. The client will exit once your application has finished running.

    With this mode, your application is actually run on the remote machine where the Application Master is run upon. Thus application that involve local interaction will not work well, e.g. spark-shell.

    0 讨论(0)
  • 2021-01-29 21:47

    Aditionally to the selected answer, if you want to connect to an external standalone Spark instance:

    SparkConf conf =
    new SparkConf()
         .setAppName("Simple Application")
         .setMaster("spark://10.3.50.139:7077");
    
    JavaSparkContext sc = new JavaSparkContext(conf);
    

    Here you can find more "master" configuration depending on where Spark is running: http://spark.apache.org/docs/latest/submitting-applications.html#master-urls

    0 讨论(0)
  • 2021-01-29 21:54

    I had the same question a few days ago and yesterday managed to solve it.
    That's what I've done:

    1. Download sbt and unzip and untar it :http://www.scala-sbt.org/download.html
    2. I have downloaded Spark Prebuild package for Hadoop 2, unzipped and untarred it: http://www.apache.org/dyn/closer.cgi/spark/spark-1.0.2/spark-1.0.2-bin-hadoop2.tgz
    3. I've created standalone application SimpleApp.scala as described in: http://spark.apache.org/docs/latest/quick-start.html#standalone-applications with proper simple.sbt file (just copied from the description) and proper directory layout
    4. Make sure you have sbt in you PATH. Go to directory with your application and build your package using sbt package
    5. Start Spark Server using SPARK_HOME_DIR/sbin/spark_master.sh
    6. Go to localhost:8080 and make sure your server is running. Copy link from URL (from server description, not localhost. It shoul be something with port 7077 or similiar)
    7. Start Workers using SPARK_HOME_DIR/bin/spark-class org.apache.spark.deploy.worker.Worker spark://IP:PORT where IP:PORT is the URL copied in 6
    8. Deploy you application to the server: SPARK_HOME_DIR/bin/spark-submit --class "SimpleApp" --master URL target/scala-2.10/simple-project_2.10-1.0.jar

    That's worked for me and hope will help you.
    Pawel

    0 讨论(0)
提交回复
热议问题