Spark getting started Idea remote submission project to spark cluster

1, Dependent package configuration

The related dependency packages of scala and spark. The number of versions underlined after spark package should be consistent with the first two digits of scala version, that is, 2.11


<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="" xmlns:xsi=""




    <!-- scala rely on-->

    <!-- spark rely on-->






2, PI example

java rewrites the PI example of scala


import org.apache.spark.SparkConf;
import org.apache.spark.sql.SparkSession;

import java.util.ArrayList;
import java.util.List;

public class App 
    public static void main( String[] args )

        SparkConf sparkConf = new SparkConf();
        if(System.getProperty("").toLowerCase().contains("win")) {
//            sparkConf.setMaster("local[2]");
//            System.out.println("spark using local emulation");
//        }else
//            {
            sparkConf.set("","");//Local ip must be able to access each other with spark cluster, such as the same LAN
            sparkConf.setJars(new String[] {".\\out\\artifacts\\spark_test\\spark-test.jar"});//Path of project build generation
        SparkSession session = SparkSession.builder().appName("Pi").config(sparkConf).config(sparkConf).getOrCreate();
        int slices =2;
        int n = (int)Math.min(100_000L * slices, Integer.MAX_VALUE);
        JavaSparkContext sparkContext = new JavaSparkContext(session.sparkContext());

        List<Integer> list = new ArrayList<>(n);
        for (int i = 0; i < n; i++)
            list.add(i + 1);
        int count  = sparkContext.parallelize(list, slices).
                map(v -> {
                    double x = Math.random() * 2 - 1;
                    double y = Math.random() * 2 - 1;
                    if (x * x + y * y < 1)
                        return 1;
                    return 0;
                }).reduce((Integer a, Integer b) ->a+b);
         System.out.println("PI:"+  4.0 * count / n);



3, Run directly on idea

Output PI



4, Limitations

Note: the local ip of the project machine must be accessible to each other with the spark cluster, such as the same LAN.

Failed to submit when not in the same network. The task has been retried and cannot exit

359 original articles published, 523 praised, 1.28 million visitors+
His message board follow

Tags: Spark Maven Scala Apache

Posted on Thu, 30 Jan 2020 10:39:11 -0500 by max_power