在学习Spark过程中,资料中介绍的提交Spark Job的方式主要有三种:

第一种:

通过命令行的方式提交Job,使用spark 自带的spark-submit工具提交,官网和大多数参考资料都是已这种方式提交的,提交命令示例如下:
./spark-submit --class com.learn.spark.SimpleApp --master yarn --deploy-mode client --driver-memory 2g --executor-memory 2g --executor-cores 3 ../spark-demo.jar
参数含义就不解释了,请参考官网资料。
 第二种:

提交方式是已JAVA API编程的方式提交,这种方式不需要使用命令行,直接可以在IDEA中点击Run 运行包含Job的Main类就行,Spark 提供了以SparkLanuncher 作为唯一入口的API来实现。这种方式很方便(试想如果某个任务需要重复执行,但是又不会写linux 脚本怎么搞?我想到的是以JAV API的方式提交Job, 还可以和Spring整合,让应用在tomcat中运行),官网的示例:http://spark.apache.org/docs/latest/api/java/index.html?org/apache/spark/launcher/package-summary.html

根据官网的示例,通过JAVA API编程的方式提交有两种方式:

第一种是调用SparkLanuncher实例的startApplication方法,但是这种方式在所有配置都正确的情况下使用运行都会失败的,原因是startApplication方法会调用LauncherServer启动一个进程与集群交互,这个操作貌似是异步的,所以可能结果是main主线程结束了这个进程都没有起起来,导致运行失败。解决办法是调用new SparkLanuncher().startApplication后需要让主线程休眠一定的时间后者是使用下面的例子:

package com.learn.spark; 

import org.apache.spark.launcher.SparkAppHandle;
import org.apache.spark.launcher.SparkLauncher; import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch; public class LanuncherAppV {
public static void main(String[] args) throws IOException, InterruptedException { HashMap env = new HashMap();
//这两个属性必须设置
env.put("HADOOP_CONF_DIR", "/usr/local/hadoop/etc/overriterHaoopConf");
env.put("JAVA_HOME", "/usr/local/java/jdk1.8.0_151");
//可以不设置
//env.put("YARN_CONF_DIR","");
CountDownLatch countDownLatch = new CountDownLatch();
//这里调用setJavaHome()方法后,JAVA_HOME is not set 错误依然存在
SparkAppHandle handle = new SparkLauncher(env)
.setSparkHome("/usr/local/spark")
.setAppResource("/usr/local/spark/spark-demo.jar")
.setMainClass("com.learn.spark.SimpleApp")
.setMaster("yarn")
.setDeployMode("cluster")
.setConf("spark.app.id", "")
.setConf("spark.driver.memory", "2g")
.setConf("spark.akka.frameSize", "")
.setConf("spark.executor.memory", "1g")
.setConf("spark.executor.instances", "")
.setConf("spark.executor.cores", "")
.setConf("spark.default.parallelism", "")
.setConf("spark.driver.allowMultipleContexts", "true")
.setVerbose(true).startApplication(new SparkAppHandle.Listener() {
//这里监听任务状态,当任务结束时(不管是什么原因结束),isFinal()方法会返回true,否则返回false
@Override
public void stateChanged(SparkAppHandle sparkAppHandle) {
if (sparkAppHandle.getState().isFinal()) {
countDownLatch.countDown();
}
System.out.println("state:" + sparkAppHandle.getState().toString());
} @Override
public void infoChanged(SparkAppHandle sparkAppHandle) {
System.out.println("Info:" + sparkAppHandle.getState().toString());
}
});
System.out.println("The task is executing, please wait ....");
//线程等待任务结束
countDownLatch.await();
System.out.println("The task is finished!"); }
}

注意:如果部署模式是cluster,但是代码中有标准输出的话将看不到,需要把结果写到HDFS中,如果是client模式则可以看到输出。

第二种方式是:通过SparkLanuncher.lanunch()方法获取一个进程,然后调用进程的process.waitFor()方法等待线程返回结果,但是使用这种方式需要自己管理运行过程中的输出信息,比较麻烦,好处是一切都在掌握之中,即获取的输出信息和通过命令提交的方式一样,很详细,实现如下:

package com.learn.spark; 

import org.apache.spark.launcher.SparkAppHandle;
import org.apache.spark.launcher.SparkLauncher; import java.io.IOException;
import java.util.HashMap; public class LauncherApp { public static void main(String[] args) throws IOException, InterruptedException { HashMap env = new HashMap();
//这两个属性必须设置
env.put("HADOOP_CONF_DIR","/usr/local/hadoop/etc/overriterHaoopConf");
env.put("JAVA_HOME","/usr/local/java/jdk1.8.0_151");
//env.put("YARN_CONF_DIR",""); SparkLauncher handle = new SparkLauncher(env)
.setSparkHome("/usr/local/spark")
.setAppResource("/usr/local/spark/spark-demo.jar")
.setMainClass("com.learn.spark.SimpleApp")
.setMaster("yarn")
.setDeployMode("cluster")
.setConf("spark.app.id", "")
.setConf("spark.driver.memory", "2g")
.setConf("spark.akka.frameSize", "")
.setConf("spark.executor.memory", "1g")
.setConf("spark.executor.instances", "")
.setConf("spark.executor.cores", "")
.setConf("spark.default.parallelism", "")
.setConf("spark.driver.allowMultipleContexts","true")
.setVerbose(true); Process process =handle.launch();
InputStreamReaderRunnable inputStreamReaderRunnable = new InputStreamReaderRunnable(process.getInputStream(), "input");
Thread inputThread = new Thread(inputStreamReaderRunnable, "LogStreamReader input");
inputThread.start(); InputStreamReaderRunnable errorStreamReaderRunnable = new InputStreamReaderRunnable(process.getErrorStream(), "error");
Thread errorThread = new Thread(errorStreamReaderRunnable, "LogStreamReader error");
errorThread.start(); System.out.println("Waiting for finish...");
int exitCode = process.waitFor();
System.out.println("Finished! Exit code:" + exitCode); }
}

使用的自定义InputStreamReaderRunnable类实现如下:

package com.learn.spark; 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; public class InputStreamReaderRunnable implements Runnable {   private BufferedReader reader;   private String name;   public InputStreamReaderRunnable(InputStream is, String name) {
    this.reader = new BufferedReader(new InputStreamReader(is));
    this.name = name;
  }   public void run() {     System.out.println("InputStream " + name + ":");
    try {
        String line = reader.readLine();
        while (line != null) {
           System.out.println(line);
           line = reader.readLine();
        }
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
   }
}

第三种方式是通过yarn的rest api的方式提交(不太常用但在这里也介绍一下):

Post请求示例: * http://<rm http address:port>/ws/v1/cluster/apps

请求所带的参数列表:

Item Data Type Description
application-id string The application id
application-name string The application name
queue string The name of the queue to which the application should be submitted
priority int The priority of the application
am-container-spec object The application master container launch context, described below
unmanaged-AM boolean Is the application using an unmanaged application master
max-app-attempts int The max number of attempts for this application
resource object The resources the application master requires, described below
application-type string The application type(MapReduce, Pig, Hive, etc)
keep-containers-across-application-attempts boolean Should YARN keep the containers used by this application instead of destroying them
application-tags object List of application tags, please see the request examples on how to speciy the tags
log-aggregation-context object Represents all of the information needed by the NodeManager to handle the logs for this application
attempt-failures-validity-interval long The failure number will no take attempt failures which happen out of the validityInterval into failure count
reservation-id string Represent the unique id of the corresponding reserved resource allocation in the scheduler
am-black-listing-requests object Contains blacklisting information such as “enable/disable AM blacklisting” and “disable failure threshold”

spark提交任务的三种的方法的更多相关文章

  1. spark提交任务的两种的方法

    在学习Spark过程中,资料中介绍的提交Spark Job的方式主要有两种(我所知道的): 第一种: 通过命令行的方式提交Job,使用spark 自带的spark-submit工具提交,官网和大多数参 ...

  2. C#使用DataSet Datatable更新数据库的三种实现方法

    本文以实例形式讲述了使用DataSet Datatable更新数据库的三种实现方法,包括CommandBuilder 方法.DataAdapter 更新数据源以及使用sql语句更新.分享给大家供大家参 ...

  3. uni-app开发经验分享一: 多页面传值的三种解决方法

    开发了一年的uni-app,在这里总结一些uni-app开发中的问题,提供几个解决方法,分享给大家: 问题描述:一个主页面,需要联通一到两个子页面,子页面传值到主页面,主页面更新 问题难点: 首先我们 ...

  4. javase-常用三种遍历方法

    javase-常用三种遍历方法 import java.util.ArrayList; import java.util.Iterator; import java.util.List; public ...

  5. JS面向对象(3) -- Object类,静态属性,闭包,私有属性, call和apply的使用,继承的三种实现方法

    相关链接: JS面向对象(1) -- 简介,入门,系统常用类,自定义类,constructor,typeof,instanceof,对象在内存中的表现形式 JS面向对象(2) -- this的使用,对 ...

  6. Java中Map的三种遍历方法

    Map的三种遍历方法: 1. 使用keySet遍历,while循环: 2. 使用entrySet遍历,while循环: 3. 使用for循环遍历.   告诉您们一个小秘密: (下↓面是测试代码,最爱看 ...

  7. Jquery中each的三种遍历方法

    Jquery中each的三种遍历方法 $.post("urladdr", { "data" : "data" }, function(dat ...

  8. spring与mybatis三种整合方法

    spring与mybatis三种整合方法 本文主要介绍Spring与Mybatis三种常用整合方法,需要的整合架包是mybatis-spring.jar,可通过链接 http://code.googl ...

  9. struts2拦截器interceptor的三种配置方法

    1.struts2拦截器interceptor的三种配置方法 方法1. 普通配置法 <struts> <package name="struts2" extend ...

随机推荐

  1. 【问题集】redis.clients.jedis.exceptions.JedisDataException: ERR value is not an integer or out of range

    redis.clients.jedis.exceptions.JedisDataException: ERR value is not an integer or out of range incrm ...

  2. 国内常用NTP服务器地址及

    210.72.145.44 (国家授时中心服务器IP地址) 133.100.11.8 日本 福冈大学 time-a.nist.gov 129.6.15.28 NIST, Gaithersburg, M ...

  3. day_11py学习

    ''' 字典增加和删除 1.添加 xxx[新的key] = value 2.删除 del xxx[key] 3.修改 xxx[已存在的key] = new_value 4.查询 xxx.get(key ...

  4. D - Lake Counting

    Due to recent rains, water has pooled in various places in Farmer John's field, which is represented ...

  5. mysql迁移sqlserver

    数据迁移的工具有很多,基本SSMA团队已经考虑到其他数据库到SQL Server迁移的需求了,所以已经开发了相关的迁移工具来支持. 此博客主要介绍MySQL到SQL Server数据迁移的工具:SQL ...

  6. Flask web开发之路二

    今天创建第一个flask项目,主app文件代码如下: # 从flask这个框架导入Flask这个类 from flask import Flask #初始化一个Flask对象 # Flasks() # ...

  7. js中if语句的几种优化代码写法

    UglifyJS是一个对javascript进行压缩和美化的工具,在它的文档说明中,我看到了几种关于if语句优化的方法. 一.使用常见的三元操作符 复制代码 代码如下: if (foo) bar(); ...

  8. NYOJ16|嵌套矩形|DP|DAG模型|记忆化搜索

    矩形嵌套 时间限制:3000 ms  |  内存限制:65535 KB 难度:4   描述 有n个矩形,每个矩形可以用a,b来描述,表示长和宽.矩形X(a,b)可以嵌套在矩形Y(c,d)中当且仅当a& ...

  9. System.InvalidOperationException: 此实现不是 Windows 平台 FIPS 验证的加密算法的一部分。

    x 昨天还好好地,然后清理一下电脑垃圾,就突然报这个错误了; 网上搜索了一下:找到解决方案了,但是由于底层知识的功力不够,至今未知具体怎么导致的... 解决方案↓ 进注册表 按Win+R运行reged ...

  10. python-----双色球实现(实例1)

    #输出用户指定组数的双色球信息,其中一组信息 6个红色号码获取范围(1-33),1个蓝色号码获取范围(1-16),要求一组信息中红球内号码不可重复 import randomdef get_ball( ...