spark apache_Apache Spark示例:Java中的字数统计程序

spark apache

Apache Spark (Apache Spark)

Apache Spark is an open source data processing framework which can perform analytic operations on Big Data in a distributed environment. It was an academic project in UC Berkley and was initially started by Matei Zaharia at UC Berkeley’s AMPLab in 2009. Apache Spark was created on top of a cluster management tool known as Mesos. This was later modified and upgraded so that it can work in a cluster based environment with distributed processing.

Apache Spark是一个开放源数据处理框架,可以在分布式环境中对大数据执行分析操作。 它是UC Berkley的一个学术项目,最初由Matei Zaharia在UC Berkeley的AMPLab于2009年启动。Apache Spark是在称为Mesos的群集管理工具之上创建的。 后来对其进行了修改和升级,使其可以在具有分布式处理的基于集群的环境中工作。

Apache Spark示例项目设置 (Apache Spark Example Project Setup)

We will be using Maven to create a sample project for the demonstration. To create the project, execute the following command in a directory that you will use as workspace:

我们将使用Maven创建一个示例项目进行演示。 要创建项目,请在将用作工作空间的目录中执行以下命令:

mvn archetype:generate -DgroupId=com.journaldev.sparkdemo -DartifactId=JD-Spark-WordCount -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

If you are running maven for the first time, it will take a few seconds to accomplish the generate command because maven has to download all the required plugins and artifacts in order to make the generation task.

如果您是第一次运行maven,则完成生成命令将需要几秒钟,因为maven必须下载所有必需的插件和工件才能完成生成任务。

Once you have created the project, feel free to open it in your favourite IDE. Next step is to add appropriate Maven Dependencies to the project. Here is the pom.xml file with the appropriate dependencies:

创建项目后,请随时在您喜欢的IDE中打开它。 下一步是向项目添加适当的Maven依赖关系。 这是带有适当依赖项的pom.xml文件:

<dependencies>

    <!-- Import Spark -->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>1.4.0</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.0.2</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                        <mainClass>com.geekcap.javaworld.sparkexample.WordCount</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                <execution>
                    <id>copy</id>
                    <phase>install</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/lib</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

As this is a maven-based project, there is actually no need to install and setup Apache Spark on your machine. When we run this project, a runtime instance of Apache Spark will be started and once the program has done executing, it will be shutdown.

由于这是一个基于Maven的项目,因此实际上无需在计算机上安装和设置Apache Spark 。 当我们运行该项目时,将启动Apache Spark的运行时实例,一旦程序执行完毕,它将关闭。

Finally, to understand all the JARs which are added to the project when we added this dependency, we can run a simple Maven command which allows us to see a complete Dependency Tree for a project when we add some dependencies to it. Here is a command which we can use:

最后,要了解添加此依赖项时添加到项目中的所有JAR,我们可以运行一个简单的Maven命令,当我们向项目添加一些依赖项时,该命令使我们能够看到项目的完整依赖关系树。 这是我们可以使用的命令:

mvn dependency:tree

When we run this command, it will show us the following Dependency Tree:

当我们运行此命令时,它将向我们显示以下依赖关系树:

shubham:JD-Spark-WordCount shubham$ mvn dependency:tree

[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for com.journaldev:java-word-count:jar:1.0-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-jar-plugin is missing. @ line 41, column 21
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] -------------------< com.journaldev:java-word-count >-------------------
[INFO] Building java-word-count 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ java-word-count ---
[INFO] com.journaldev:java-word-count:jar:1.0-SNAPSHOT
[INFO] +- org.apache.spark:spark-core_2.11:jar:1.4.0:compile
[INFO] |  +- com.twitter:chill_2.11:jar:0.5.0:compile
[INFO] |  |  \- com.esotericsoftware.kryo:kryo:jar:2.21:compile
[INFO] |  |     +- com.esotericsoftware.reflectasm:reflectasm:jar:shaded:1.07:compile
[INFO] |  |     +- com.esotericsoftware.minlog:minlog:jar:1.2:compile
[INFO] |  |     \- org.objenesis:objenesis:jar:1.2:compile
[INFO] |  +- com.twitter:chill-java:jar:0.5.0:compile
[INFO] |  +- org.apache.hadoop:hadoop-client:jar:2.2.0:compile
[INFO] |  |  +- org.apache.hadoop:hadoop-common:jar:2.2.0:compile
[INFO] |  |  |  +- commons-cli:commons-cli:jar:1.2:compile
[INFO] |  |  |  +- org.apache.commons:commons-math:jar:2.1:compile
[INFO] |  |  |  +- xmlenc:xmlenc:jar:0.52:compile
[INFO] |  |  |  +- commons-io:commons-io:jar:2.1:compile
[INFO] |  |  |  +- commons-logging:commons-logging:jar:1.1.1:compile
[INFO] |  |  |  +- commons-lang:commons-lang:jar:2.5:compile
[INFO] |  |  |  +- commons-configuration:commons-configuration:jar:1.6:compile
[INFO] |  |  |  |  +- commons-collections:commons-collections:jar:3.2.1:compile
[INFO] |  |  |  |  +- commons-digester:commons-digester:jar:1.8:compile
[INFO] |  |  |  |  |  \- commons-beanutils:commons-beanutils:jar:1.7.0:compile
[INFO] |  |  |  |  \- commons-beanutils:commons-beanutils-core:jar:1.8.0:compile
[INFO] |  |  |  +- org.codehaus.jackson:jackson-core-asl:jar:1.8.8:compile
[INFO] |  |  |  +- org.apache.avro:avro:jar:1.7.4:compile
[INFO] |  |  |  +- com.google.protobuf:protobuf-java:jar:2.5.0:compile
[INFO] |  |  |  +- org.apache.hadoop:hadoop-auth:jar:2.2.0:compile
[INFO] |  |  |  \- org.apache.commons:commons-compress:jar:1.4.1:compile
[INFO] |  |  |     \- org.tukaani:xz:jar:1.0:compile
[INFO] |  |  +- org.apache.hadoop:hadoop-hdfs:jar:2.2.0:compile
[INFO] |  |  |  \- org.mortbay.jetty:jetty-util:jar:6.1.26:compile
[INFO] |  |  +- org.apache.hadoop:hadoop-mapreduce-client-app:jar:2.2.0:compile
[INFO] |  |  |  +- org.apache.hadoop:hadoop-mapreduce-client-common:jar:2.2.0:compile
[INFO] |  |  |  |  +- org.apache.hadoop:hadoop-yarn-client:jar:2.2.0:compile
[INFO] |  |  |  |  |  +- com.google.inject:guice:jar:3.0:compile
[INFO] |  |  |  |  |  |  +- javax.inject:javax.inject:jar:1:compile
[INFO] |  |  |  |  |  |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  |  |  |  |  +- com.sun.jersey.jersey-test-framework:jersey-test-framework-grizzly2:jar:1.9:compile
[INFO] |  |  |  |  |  |  +- com.sun.jersey.jersey-test-framework:jersey-test-framework-core:jar:1.9:compile
[INFO] |  |  |  |  |  |  |  +- javax.servlet:javax.servlet-api:jar:3.0.1:compile
[INFO] |  |  |  |  |  |  |  \- com.sun.jersey:jersey-client:jar:1.9:compile
[INFO] |  |  |  |  |  |  \- com.sun.jersey:jersey-grizzly2:jar:1.9:compile
[INFO] |  |  |  |  |  |     +- org.glassfish.grizzly:grizzly-https:jar:2.1.2:compile
[INFO] |  |  |  |  |  |     |  \- org.glassfish.grizzly:grizzly-framework:jar:2.1.2:compile
[INFO] |  |  |  |  |  |     |     \- org.glassfish.gmbal:gmbal-api-only:jar:3.0.0-b023:compile
[INFO] |  |  |  |  |  |     |        \- org.glassfish.external:management-api:jar:3.0.0-b012:compile
[INFO] |  |  |  |  |  |     +- org.glassfish.grizzly:grizzly-http-server:jar:2.1.2:compile
[INFO] |  |  |  |  |  |     |  \- org.glassfish.grizzly:grizzly-rcm:jar:2.1.2:compile
[INFO] |  |  |  |  |  |     +- org.glassfish.grizzly:grizzly-http-servlet:jar:2.1.2:compile
[INFO] |  |  |  |  |  |     \- org.glassfish:javax.servlet:jar:3.1:compile
[INFO] |  |  |  |  |  +- com.sun.jersey:jersey-json:jar:1.9:compile
[INFO] |  |  |  |  |  |  +- org.codehaus.jettison:jettison:jar:1.1:compile
[INFO] |  |  |  |  |  |  |  \- stax:stax-api:jar:1.0.1:compile
[INFO] |  |  |  |  |  |  +- com.sun.xml.bind:jaxb-impl:jar:2.2.3-1:compile
[INFO] |  |  |  |  |  |  |  \- javax.xml.bind:jaxb-api:jar:2.2.2:compile
[INFO] |  |  |  |  |  |  |     \- javax.activation:activation:jar:1.1:compile
[INFO] |  |  |  |  |  |  +- org.codehaus.jackson:jackson-jaxrs:jar:1.8.3:compile
[INFO] |  |  |  |  |  |  \- org.codehaus.jackson:jackson-xc:jar:1.8.3:compile
[INFO] |  |  |  |  |  \- com.sun.jersey.contribs:jersey-guice:jar:1.9:compile
[INFO] |  |  |  |  \- org.apache.hadoop:hadoop-yarn-server-common:jar:2.2.0:compile
[INFO] |  |  |  \- org.apache.hadoop:hadoop-mapreduce-client-shuffle:jar:2.2.0:compile
[INFO] |  |  +- org.apache.hadoop:hadoop-yarn-api:jar:2.2.0:compile
[INFO] |  |  +- org.apache.hadoop:hadoop-mapreduce-client-core:jar:2.2.0:compile
[INFO] |  |  |  \- org.apache.hadoop:hadoop-yarn-common:jar:2.2.0:compile
[INFO] |  |  +- org.apache.hadoop:hadoop-mapreduce-client-jobclient:jar:2.2.0:compile
[INFO] |  |  \- org.apache.hadoop:hadoop-annotations:jar:2.2.0:compile
[INFO] |  +- org.apache.spark:spark-launcher_2.11:jar:1.4.0:compile
[INFO] |  +- org.apache.spark:spark-network-common_2.11:jar:1.4.0:compile
[INFO] |  +- org.apache.spark:spark-network-shuffle_2.11:jar:1.4.0:compile
[INFO] |  +- org.apache.spark:spark-unsafe_2.11:jar:1.4.0:compile
[INFO] |  +- net.java.dev.jets3t:jets3t:jar:0.7.1:compile
[INFO] |  |  +- commons-codec:commons-codec:jar:1.3:compile
[INFO] |  |  \- commons-httpclient:commons-httpclient:jar:3.1:compile
[INFO] |  +- org.apache.curator:curator-recipes:jar:2.4.0:compile
[INFO] |  |  +- org.apache.curator:curator-framework:jar:2.4.0:compile
[INFO] |  |  |  \- org.apache.curator:curator-client:jar:2.4.0:compile
[INFO] |  |  +- org.apache.zookeeper:zookeeper:jar:3.4.5:compile
[INFO] |  |  |  \- jline:jline:jar:0.9.94:compile
[INFO] |  |  \- com.google.guava:guava:jar:14.0.1:compile
[INFO] |  +- org.eclipse.jetty.orbit:javax.servlet:jar:3.0.0.v201112011016:compile
[INFO] |  +- org.apache.commons:commons-lang3:jar:3.3.2:compile
[INFO] |  +- org.apache.commons:commons-math3:jar:3.4.1:compile
[INFO] |  +- com.google.code.findbugs:jsr305:jar:1.3.9:compile
[INFO] |  +- org.slf4j:slf4j-api:jar:1.7.10:compile
[INFO] |  +- org.slf4j:jul-to-slf4j:jar:1.7.10:compile
[INFO] |  +- org.slf4j:jcl-over-slf4j:jar:1.7.10:compile
[INFO] |  +- log4j:log4j:jar:1.2.17:compile
[INFO] |  +- org.slf4j:slf4j-log4j12:jar:1.7.10:compile
[INFO] |  +- com.ning:compress-lzf:jar:1.0.3:compile
[INFO] |  +- org.xerial.snappy:snappy-java:jar:1.1.1.7:compile
[INFO] |  +- net.jpountz.lz4:lz4:jar:1.2.0:compile
[INFO] |  +- org.roaringbitmap:RoaringBitmap:jar:0.4.5:compile
[INFO] |  +- commons-net:commons-net:jar:2.2:compile
[INFO] |  +- org.spark-project.akka:akka-remote_2.11:jar:2.3.4-spark:compile
[INFO] |  |  +- org.spark-project.akka:akka-actor_2.11:jar:2.3.4-spark:compile
[INFO] |  |  |  \- com.typesafe:config:jar:1.2.1:compile
[INFO] |  |  +- io.netty:netty:jar:3.8.0.Final:compile
[INFO] |  |  +- org.spark-project.protobuf:protobuf-java:jar:2.5.0-spark:compile
[INFO] |  |  \- org.uncommons.maths:uncommons-maths:jar:1.2.2a:compile
[INFO] |  +- org.spark-project.akka:akka-slf4j_2.11:jar:2.3.4-spark:compile
[INFO] |  +- org.scala-lang:scala-library:jar:2.11.6:compile
[INFO] |  +- org.json4s:json4s-jackson_2.11:jar:3.2.10:compile
[INFO] |  |  \- org.json4s:json4s-core_2.11:jar:3.2.10:compile
[INFO] |  |     +- org.json4s:json4s-ast_2.11:jar:3.2.10:compile
[INFO] |  |     \- org.scala-lang:scalap:jar:2.11.0:compile
[INFO] |  |        \- org.scala-lang:scala-compiler:jar:2.11.0:compile
[INFO] |  |           +- org.scala-lang.modules:scala-xml_2.11:jar:1.0.1:compile
[INFO] |  |           \- org.scala-lang.modules:scala-parser-combinators_2.11:jar:1.0.1:compile
[INFO] |  +- com.sun.jersey:jersey-server:jar:1.9:compile
[INFO] |  |  \- asm:asm:jar:3.1:compile
[INFO] |  +- com.sun.jersey:jersey-core:jar:1.9:compile
[INFO] |  +- org.apache.mesos:mesos:jar:shaded-protobuf:0.21.1:compile
[INFO] |  +- io.netty:netty-all:jar:4.0.23.Final:compile
[INFO] |  +- com.clearspring.analytics:stream:jar:2.7.0:compile
[INFO] |  +- io.dropwizard.metrics:metrics-core:jar:3.1.0:compile
[INFO] |  +- io.dropwizard.metrics:metrics-jvm:jar:3.1.0:compile
[INFO] |  +- io.dropwizard.metrics:metrics-json:jar:3.1.0:compile
[INFO] |  +- io.dropwizard.metrics:metrics-graphite:jar:3.1.0:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.4.4:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.4.0:compile
[INFO] |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.4.4:compile
[INFO] |  +- com.fasterxml.jackson.module:jackson-module-scala_2.11:jar:2.4.4:compile
[INFO] |  |  +- org.scala-lang:scala-reflect:jar:2.11.2:compile
[INFO] |  |  \- com.thoughtworks.paranamer:paranamer:jar:2.6:compile
[INFO] |  +- org.apache.ivy:ivy:jar:2.4.0:compile
[INFO] |  +- oro:oro:jar:2.0.8:compile
[INFO] |  +- org.tachyonproject:tachyon-client:jar:0.6.4:compile
[INFO] |  |  \- org.tachyonproject:tachyon:jar:0.6.4:compile
[INFO] |  +- net.razorvine:pyrolite:jar:4.4:compile
[INFO] |  +- net.sf.py4j:py4j:jar:0.8.2.1:compile
[INFO] |  \- org.spark-project.spark:unused:jar:1.0.0:compile
[INFO] \- junit:junit:jar:4.11:test
[INFO]    \- org.hamcrest:hamcrest-core:jar:1.3:test
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.987 s
[INFO] Finished at: 2018-04-07T15:50:34+05:30
[INFO] ------------------------------------------------------------------------

With just two added dependencies, Spark collected all the required dependencies in the project which includes Scala dependencies as well as Apache Spark is written in Scala itself.

仅添加了两个依赖关系,Spark收集了项目中所有必需的依赖关系,其中包括Scala依赖关系以及Apache Spark是用Scala本身编写的。

创建输入文件 (Creating an Input File)

As we’re going to create a Word Counter program, we will create a sample input file for our project in the root directory of our project with name input.txt. Put any content inside it, we use the following text:

在创建Word Counter程序时,我们将在项目的根目录中为项目创建一个示例输入文件,名称为input.txt。 将任何内容放入其中,我们使用以下文本:

Hello, my name is Shubham and I am author at JournalDev . JournalDev is a great website to ready
great lessons about Java, Big Data, Python and many more Programming languages.

Big Data lessons are difficult to find but at JournalDev , you can find some excellent
pieces of lessons written on Big Data.

Feel free to use any text in this file.

随时使用此文件中的任何文本。

项目结构 (Project Structure)

Before we move on and start working on the code for the project, let’s present here the project structure we will have once we’re finished adding all the code to the project:

在继续进行并开始处理项目代码之前,让我们在这里介绍完成所有代码添加到项目后将拥有的项目结构:

apache spark example project structure

Project Structure

项目结构

创建WordCounter (Creating the WordCounter)

Now, we’re ready to start writing our program. When you start working with Big Data programs, imports can create a lot of confusion. To avoid this, here are all the imports we will use in our project:

现在,我们准备开始编写程序。 当您开始使用大数据程序时,导入会造成很多混乱。 为避免这种情况,以下是我们将在项目中使用的所有导入:

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;

import java.util.Arrays;

Next, here is the structure of our class which we will be using:

接下来,这是我们将使用的类的结构:

package com.journaldev.sparkdemo;

...imports...

public class WordCounter {

    private static void wordCount(String fileName) {
        ...
    }

    public static void main(String[] args) {
        ...
    }
}

All the logic will lie inside the wordCount method. We will start by defining an object for the SparkConf class. The object this class is used to set various Spark parameters as key-value pairs for the program. We provide just simple parameters:

所有逻辑将位于wordCount方法内。 我们将从为SparkConf类定义一个对象开始。 此类的对象用于将各种Spark参数设置为程序的键值对。 我们只提供简单的参数:

SparkConf sparkConf = new SparkConf().setMaster("local").setAppName("JD Word Counter");

The master specifies local which means that this program should connect to Spark thread running on the localhost. App name is just a way to provide Spark with the application metadata. Now, we can construct a Spark Context object with this configuration object:

master指定本地,这意味着该程序应连接到在localhost上运行的Spark线程。 应用程序名称只是向Spark提供应用程序元数据的一种方式。 现在,我们可以使用以下配置对象构造一个Spark Context对象:

JavaSparkContext sparkContext = new JavaSparkContext(sparkConf);

Spark considers every resource it gets to process as an RDD (Resilient Distributed Datasets) which helps it to organise the data in a find data structure which is much more efficient to be analysed. We will now convert the input file to a JavaRDD object itself:

Spark将其要处理的每个资源都视为RDD(弹性分布式数据集),这有助于其将数据组织到查找数据结构中,从而更有效地进行分析。 现在,我们将输入文件转换为JavaRDD对象本身:

JavaRDD<String> inputFile = sparkContext.textFile(fileName);

We will now use Java 8 APIs to process the JavaRDD file and split the words the file contains into separate words:

现在,我们将使用Java 8 API处理JavaRDD文件,并将文件中包含的单词拆分为单独的单词:

JavaRDD<String> wordsFromFile = inputFile.flatMap(content -> Arrays.asList(content.split(" ")));

Again, we make use of Java 8 mapToPair(...) method to count the words and provide a word, number pair which can be presented as an output:

同样,我们利用Java 8 mapToPair(...)方法对单词进行计数,并提供一个word, number对,可以将其显示为输出:

JavaPairRDD countData = wordsFromFile.mapToPair(t -> new Tuple2(t, 1)).reduceByKey((x, y) -> (int) x + (int) y);

Now, we can save the output file as a text file:

现在,我们可以将输出文件另存为文本文件:

countData.saveAsTextFile("CountData");

Finally, we can provide the entry point to our program with the main() method:

最后,我们可以使用main()方法为程序提供入口点:

public static void main(String[] args) {
    if (args.length == 0) {
        System.out.println("No files provided.");
        System.exit(0);
    }
    wordCount(args[0]);
}

The complete file looks like:

完整的文件如下所示:

package com.journaldev.sparkdemo;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;

import java.util.Arrays;

public class WordCounter {

    private static void wordCount(String fileName) {

        SparkConf sparkConf = new SparkConf().setMaster("local").setAppName("JD Word Counter");

        JavaSparkContext sparkContext = new JavaSparkContext(sparkConf);

        JavaRDD<String> inputFile = sparkContext.textFile(fileName);

        JavaRDD<String> wordsFromFile = inputFile.flatMap(content -> Arrays.asList(content.split(" ")));

        JavaPairRDD countData = wordsFromFile.mapToPair(t -> new Tuple2(t, 1)).reduceByKey((x, y) -> (int) x + (int) y);

        countData.saveAsTextFile("CountData");
    }

    public static void main(String[] args) {

        if (args.length == 0) {
            System.out.println("No files provided.");
            System.exit(0);
        }

        wordCount(args[0]);
    }
}

We will now move forward to run this program using Maven itself.

现在,我们将继续使用Maven本身运行该程序。

运行应用程序 (Running the Application)

To run the application, go inside the root directory of the program and execute the following command:

要运行该应用程序,请进入程序的根目录并执行以下命令:

mvn exec:java -Dexec.mainClass=com.journaldev.sparkdemo.WordCounter -Dexec.args="input.txt"

In this command, we provide Maven with the fully-qualified name of the Main class and the name for input file as well. Once this command is done executing, we can see a new directory is created in our project:

在此命令中,我们为Maven提供Main类的全限定名称以及输入文件的名称。 执行完此命令后,我们可以看到在项目中创建了一个新目录:

apache spark example output directory

Project Output Directory

项目输出目录

When we open the directory and the file named “part-00000.txt” inside it, its contents are as follows:

打开目录和其中的名为“ part-00000.txt”的文件时,其内容如下:

apache spark word count example output

Word Counter Output

字计数器输出

结论 (Conclusion)

In this lesson, we saw how we can use Apache Spark in a Maven-based project to make a simple but effective Word counter program. Read more Big Data Posts to gain deeper knowledge of available Big Data tools and processing frameworks.

在本课程中,我们了解了如何在基于Maven的项目中使用Apache Spark来制作简单但有效的Word计数器程序。 阅读更多有关大数据的文章,以更深入地了解可用的大数据工具和处理框架。

下载源代码 (Download the Source Code)

翻译自: https://www.journaldev.com/20342/apache-spark-example-word-count-program-java

spark apache

Java 与 Apache Spark 集成:打造数据处理的超级英雄 Apache Spark 是一个开源的大规模数据处理框架,它提供了一个统一的编程模型,用于执行批处理、流处理、机器学习和图形处理等任务。Spark 的核心优势在于它的速度和易用性。由于 Spark 的 Java API 不像 Scala API 那样提供了方便的元组类型,我们需要自定义一个Pair类来模仿 Scala 中的元组。通过这篇俏皮可爱的指南,我们不仅了解了如何使用 Java 集成 Apache Spark,还学习了如何编写简单的数据处理应用程序。 阅读详情

相关推荐

ApacheSparkJavaDemo:Java中的Apache Spark示例

sparkTutorial James Lee的《 Aparch Spark with Java》课程的项目源代码。 查看James和Tao教授的DevOps和大数据课程的完整列表。

Java接入Apache Spark(入门环境搭建、常见问题)

Apache官网:https://spark.apache.org/将下载好的hadoop-3.3.6.tar.gz包,放到想要安装的目录,我这里是放在D盘(D:\hadoop-3.3.6.tar.gz)解压hadoop-3.3.6.tar.gz文件【注意:需要在cmd中以管理员身份运行】 进入文件目录 等待执行结束配置HADOOP_HOME环境变量,进入 此电脑 -> 右键 -> 属性 -> 高级系统设置 -> 环境变量 选择新建,配置变量名 HADOOP_HOME ,变量值为 hadoop的解压路径

qq_43170312的博客 3842

别再死记硬背了!用LabVIEW串口通信的3个真实项目案例,手把手教你从调试到部署

本文通过3个真实项目案例,详细讲解LabVIEW串口通信从调试到部署的全过程。涵盖Arduino温湿度监控、西门子PLC Modbus通信以及高可靠性通信框架设计,提供实用技巧和常见问题解决方案,帮助工程师快速掌握LabVIEW串口通信的实战应用。

weixin_30485379的博客 536

Java使用Spark入门级非常详细的总结

本文介绍了如何使用Java编写Spark应用程序。我们首先创建了一个SparkContext对象,然后使用textFile方法读取了一个文本文件,并使用flatMap和reduceByKey方法计算了单词出现的次数。最后,我们使用spark-submit命令运行了应用程序。

qq_37480069的博客 1万+

【移远EG800K-CN】从AT指令到MQTT实战:4G模块云端通信全解析

本文详细解析移远EG800K-CN 4G模块的AT指令应用与MQTT云端通信实战。从硬件连接到网络配置,再到MQTT协议的数据上报与命令接收,提供了完整的物联网通信解决方案,帮助开发者快速实现设备与云端的稳定数据交互。

o1p2q3r的博客 579

手把手教你用Simulink搭建PMSM FOC控制模型(附完整仿真文件下载)

本文手把手教你使用Simulink搭建完整的永磁同步电机(PMSM)磁场定向控制(FOC)仿真模型。内容涵盖从电机与逆变器建模、核心的坐标变换(Clark/Park变换)实现、电流环与速度环PID整定,到SVPWM调制与系统集成调试的全过程,并提供关键参数设置与实用调试技巧,帮助工程师快速掌握FOC的工程实现。

silver的专栏 872

Java Spark 操作 Apache Kudu

`Apache Kudu`是一种列式分布式存储引擎,它的设计目标是支持快速分析和高吞吐量的数据访问,同时也能够支持低延迟、实时查询和更新操作。它被称为`Hadoop`生态系统的新一代存储层,能够与`Apache Spark、Apache Impala、Apache Hive`等大数据处理框架集成使用。

小毕超博客 1292

杰理AC2005B省晶振BLE芯片实测:内部RC自校准能否取代外部晶振?

低功耗蓝牙(BLE)是物联网设备无线连接的主流方案,其射频载波对频率精度要求极高,传统设计离不开外部晶振作为参考时钟。然而晶振及其外围电路占据不少成本与PCB面积,促使芯片厂商探索省晶振方案。这类方案采用内部RC振荡器配合自校准技术,通过出厂校准与在线频率修正,将频偏压回协议允许范围。其技术价值在于降低BOM成本、简化布局,尤其适合遥控器、电子价签、Beacon等对成本敏感、连接简单的产品。本文针对杰理AC2005B这颗省晶振BLE芯片进行DEMO板实测,覆盖功耗、射频频偏、温度漂移等关键指标,验证省晶振设

weixin_34216614的博客 279

spark 示例_带有示例和用例的Apache Spark简介

spark 示例 当我对Scala(Spark的编写语言)感兴趣时,我在2013年底首次听说了Spark。 一段时间后,我做了一个有趣的数据科学项目,试图预测泰坦尼克号上的生存情况 。 事实证明,这是进一步介绍Spark概念和编程的好方法。 我强烈建议有志向的Spark开发人员寻找入门的地方。 今天,Spark已被亚马逊,eBay和Yahoo!等主要公司采用。 许多组织在具有数千个节点的...

danpu0978的博客 413

地瓜机器人RDK Studio使用入门教程

不知道大家在使用AI开发板的时候有没有遇到过板子官方镜像占据空间大难以保存,想要的时候找不到?官方示例项目久而久之便难以找寻?首次登陆开发板连接网络还需要准备显示器键盘鼠标外设繁杂?…为了解决平时开发过程中遇到的种种不便利问题,地瓜机器人创新的推出了RDK Studio这一官方开发者软件,使智能机器人开发迎来新纪元!通过这一软件极大降低了机器人的开发门槛,哪怕是零基础的用户亦可轻松上手RDK系列板卡!

xiongqi123123的博客 3454

RK3588 DDR5 方案

RK3588 DDR5方案支持多种LPDDR5/LPDDR5X内存型号,包括美光、三星、海力士、江波龙和佰维等品牌。文档详细列出了已验证的DDR5内存规格,涵盖2GB-16GB容量范围,提供组织形式、封装类型和测试状态等信息。其中美光型号最全面,支持12GB/16GB大容量方案。部分型号处于测试验证阶段(T/A),需量产进一步确认性能。该方案为RK3588平台开发提供可靠的内存选型参考。

501846585_QQAndroid_java 1122

带有示例和用例的Apache Spark简介

当我对Scala(Spark的编写语言)感兴趣时,我在2013年底首次听说了Spark。 一段时间后,我做了一个有趣的数据科学项目,试图预测《泰坦尼克号》的生存情况 。 事实证明,这是进一步介绍Spark概念和编程的好方法。 我强烈建议有志向的Spark开发人员寻找入门的地方。 如今,Spark已被Amazon,eBay和Yahoo!等主要公司采用。 许多组织在具有数千个节点的群集上运行...

danpu0978的博客 286

【大语言模型 14】Transformer权重初始化策略:从Xavier到GPT的参数初始化演进之路

权重初始化是深度学习训练成功的隐秘基石,特别是在Transformer这样的深层架构中,合适的初始化策略能够决定模型的训练稳定性和收敛速度。本文从经典的Xavier和He初始化出发,深入解析Transformer特有的初始化策略,通过数学推导、代码实现和实验分析,揭示不同初始化方法对大语言模型训练的深层影响。我们将探讨为什么GPT系列模型采用特定的初始化方案,以及如何针对不同层设计最优的初始化策略。

熵数实验室 1692

Apache Spark RDD和Java流

几个月前,我很幸运地参加了一些使用Apache Spark的PoC(概念验证)。 在这里,我有机会使用弹性分布式数据集(简称RDD ),转换和操作。 几天后,我意识到虽然Apache Spark和JDK是非常不同的平台,但RDD转换和操作以及流中间操作和终端操作之间存在相似之处。 我认为这些相似之处可以帮助初学者(如我* grin * )开始使用Apache Spark。 Jav...

最佳 Java 编程 413

【3D Slicer】的小白入门使用指南一

3D Slicer 是一个免费的开源软件平台,用于医学、生物医学和其他 3D 图像的可视化、处理、分割、配准和分析。Slicer 的功能包括:读/写。

图挖掘领域,新晋砖家 ☞ 未来可期,欢迎和静静一起学习交流吖 5574

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

用Apache Spark进行大数据处理四

如何安装Spark 安装和使用Spark有几种不同方式。你可以在自己的电脑上将Spark作为一个独立的框架安装或者从诸如Cloudera,HortonWorks或MapR之类的供应商处获取一个Spark虚拟机镜像直接使用。或者你也可以使用在云端环境(如Databricks Cloud)安装并配置好的Spark。 在本文中,我们将把Spark作为一个独立的框架安装并在本地启动它。最近Spar

老吴的私房菜 2661

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

WordCount对比spark——java

使用spark编写的WordCount! package com.test import org.apache.spark.{SparkConf, SparkContext} object Spark_Test { def main(args: Array[String]): Unit = { val sparkConf = new SparkCo...

avz73655的博客 159

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

spark中的累加器和广播变量使用

1.准备数据 spark,java,#,! spark,java spark,python,% hello,java java,!,% 2.需求:统计字符串字数和特殊字符的总数 3.代码展示和注释详解 在这里插入代码片 /声明一个累加器 val mycounter: LongAccumulator = sc.longAccumulator("mycounter") //准备/加载规则(就是一些定义好的特殊字符) val ruleList: List[String] = List(",",".","

m0_48714980的博客 195

Spark3.x指北——1:Spark基础概念

Spark 集群的独立部署环境中,不需要依赖其他的资源调度框架,自身就实现了资源调 度的功能,所以环境中还有其他两个核心组件:Master和Worker,这里的Master是一个进 程,主要负责资源的调度和分配,并进行集群的监控等职责,类似于Yarn环境中的RM, 而 Worker 呢,也是进程,一个Worker运行在集群中的一台服务器上,由Master分配资源对 数据进行并行的处理和计算,类似于Yarn环境中NM。接下来,就让咱们走进Spark的世界,了解一下它是如何带领 我们完成数据处理的。

2302_80256936的博客 460

reducebykey java_Spark入门(五)--Spark的reduce和reduceByKey

reduce和reduceByKey的区别reduce和reduceByKey是spark中使用地非常频繁的,在字数统计中,可以看到reduceByKey的经典使用。那么reduce和reduceBykey的区别在哪呢?reduce处理数据时有着一对一的特性,而reduceByKey则有着多对一的特性。比如reduce中会把数据集合中每一个元素都处理一次,并且每一个元素都对应着一个输出。而redu...

weixin_26704349的博客 1079

Spark入门(Python版)

Hadoop是对大数据集进行分布式计算的标准工具,这也是为什么当你穿过机场时能看到”大数据(Big Data)”广告的原因。它已经成为大数据的操作系统,提供了包括工具和技巧在内的丰富生态系统,允许使用相对便宜的商业硬件集群进行超级计算机级别的计算。2003和2004年,两个来自Google的观点使Hadoop成为可能:一个分布式存储框架(Google文件系统),在Hadoop中被实现为HDFS;一

清晨随笔 735

spark入门(1)

Spark是什么? 既然设置好了Spark,现在我们讨论下Spark是什么。Spark是个通用的集群计算框架,通过将大量数据集计算任务分配到多台计算机上,提供高效内存计算。如果你熟悉Hadoop,那么你知道分布式计算框架要解决两个问题:如何分发数据和如何分发计算。Hadoop使用HDFS来解决分布式数据问题,MapReduce计算范式提供有效的分布式计算。类似的,Spark拥有多种语言的函数

软件工程小施同学 的专栏 832

在 Azure HDInsight 中安装和使用 Spark

Spark本身用Scala语言编写,运行于Java虚拟机(JVM)。只要在安装了Java 6以上版本的便携式计算机或者集群上都可以运行spark。如果您想使用Python API需要安装Python解释器(2.6或者更高版本),请注意Spark暂不支持Python 3。 下载Spark 首先下载Spark并解压,我们从下载预编译版本的Spark开始。在浏览器中访问 htt...

aiguai19961210的博客 320

电脑安装Spark教程,Windows本地搭建步骤详解

在自己电脑上安装Spark,既能作为学习大数据处理的起点,也能为个人数据分析项目提供强大的计算能力。这个过程并不复杂,通过几个关键步骤,你就可以搭建一个本地的Spark开发环境

2509_93883384的博客 368

Spark入门(1-4)安装、运行Spark

如何安装Spark 安装和使用Spark有几种不同方式。你可以在自己的电脑上将Spark作为一个独立的框架安装或者从诸如Cloudera,HortonWorks或MapR之类的供应商处获取一个Spark虚拟机镜像直接使用。或者你也可以使用在云端环境(如Databricks Cloud)安装并配置好的Spark。 在本文中,我们将把Spark作为一个独立的框架安装并在本地启动它。最近Spark刚刚发...

weixin_34150224的博客 174
上一篇: 微信web开发工具如何使用_优秀的设计师和开发人员使用出色的Web开发工具
下一篇: 带有第三方工具的Spring Boot Initilizr
cunchi4221
博客等级 码龄11年 643粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值