创建maven项目:
打包的时候注意修改成自己项目的包名。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fengling</groupId>
<artifactId>streaming</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spark.version>2.1.1</spark.version>
<scala.version>2.11.12</scala.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming_2.11</artifactId>
<version>${spark.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>${spark.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
<!--<scope>provided</scope>-->
</dependency>
</dependencies>
<build>
<plugins>
<!--添加编译支持,都编译成java1.8版本-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!--添加Scala编译支持-->
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>3.2.2</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<archive>
<manifest>
<mainClass>com.fengling.WordCount</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
创建WordCount类
package com.fengling
import org.apache.spark.SparkConf
import org.apache.spark.streaming.{Seconds, StreamingContext}
/**
* @author fengchengliang@126.com
* @date 2019-10-26
*/
object WordCount extends App {
// 创建StreamingContext
val conf = new SparkConf().setMaster("local[4]").setAppName("StreamingWordCount ;)")
val ssc = new StreamingContext(conf, Seconds(1))
// 创建DStream 连接到hadoop129:9999
val lines = ssc.socketTextStream("hadoop129", 9999)
// 每行输入按空格切分成一个个单词
val words = lines.flatMap(_.split(" "))
val pairs = words.map(word => (word, 1))
val wordCount = pairs.reduceByKey((_ + _))
wordCount.print()
ssc.start()
ssc.awaitTermination()
}
打jar包并上传到服务器。
运行jar
[fengling@hadoop129 spark-2.4.4-bin-hadoop2.7]$ bin/spark-submit --class com.fengling.WordCount ~/streaming-1.0-SNAPSHOT-jar-with-dependencies.jar
终端执行nc命令:
[fengling@hadoop129 ~]$ nc -lk 9999