Ubuntu 14.04 下使用IDEA开发Spark应用 入门
网上有很多教程,有用sbt ,也有不用sbt的,看的头大,搞了半天,终于运行成功一个例子,如下:
1.官网下载http://www.jetbrains.com/idea/download/
Interlij IDEA,用conmmunity Edition 就够了
2.启动起来以后,在插件搜索里面 选择scala ,安装。
3.创建scala Project ,设置名称,JDK和Scala路径:
4.选择菜单中的“File”→“project structure”→“Libraries”,然后点击“+”导入spark-assembly-1.2.0-hadoop2.4.0.jar。
这个jar包包含Spark的所有依赖包和Spark源码。
5.新建一个SparkPi的类,最终结果如下:
6.代码如下:
/** * Created by hadoop on 15-12-15. */ package org.apache.spark.examples import scala.math.random import org.apache.spark.SparkContext import org.apache.spark.SparkContext._ /** Computes an approximation to pi */ object SparkPi { def main(args: Array[String]) { // val conf = new SparkConf().setAppName("Spark Pi").setMaster("spark://127.0.0.1:7077") // val spark = new SparkContext(conf) val spark = new SparkContext("local","Spark Pi") val slices = if (args.length > 0) args(0).toInt else 2 val n = math.min(100000L * slices, Int.MaxValue).toInt // avoid overflow val count = spark.parallelize(1 until n, slices).map { i => val x = random * 2 - 1 val y = random * 2 - 1 if (x*x + y*y < 1) 1 else 0 }.reduce(_ + _) println("Pi is roughly " + 4.0 * count / n) spark.stop() } }
7.运行Spark程序像上面我们编写完代码,有两种方法运行我们的程序,一个是IDEA中的run方法,另一个是将我们的程序打包成jar包,在Spark集群上用命令行执行。
Run方法:
在IDEA菜单中选择“Run”→“Edit Configurations”出现如下界面:
点左上角的“+”,选择“Application”,在右边的拓展中改一下name,选择Main函数:
然后点击右上角的绿色运行箭头即可
错误处理:
[error] (run-main-0) java.lang.NoSuchMethodError: scala.collection.immutable.HashSet$.empty()Lscala/collection/immutable/HashSet; java.lang.NoSuchMethodError: scala.collection.immutable.HashSet$.empty()Lscala/collection/immutable/HashSet; at akka.actor.ActorCell$.<init>(ActorCell.scala:305) at akka.actor.ActorCell$.<clinit>(ActorCell.scala) at akka.actor.RootActorPath.$div(ActorPath.scala:152) at akka.actor.LocalActorRefProvider.<init>(ActorRefProvider.scala:465) at akka.remote.RemoteActorRefProvider.<init>(RemoteActorRefProvider.scala:124) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:422) at akka.actor.ReflectiveDynamicAccess$$anonfun$createInstanceFor$2.apply(DynamicAccess.scala:78) at scala.util.Try$.apply(Try.scala:191)
解决办法:将scala2.11换成scala2.10