您好,登錄后才能下訂單哦!
這篇文章主要講解了“Spark Stream怎么使用”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Spark Stream怎么使用”吧!
pom.xml
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-streaming_2.11</artifactId>
<version>2.1.0</version>
</dependency>
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.UUID;
import org.apache.spark.SparkConf;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import scala.Tuple2;
public class SparkStreamTest {
public static void main(String[] args) throws Exception {
startSockerServer(9999);
SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("NetworkWordCount");
JavaStreamingContext jssc = new JavaStreamingContext(conf, Durations.seconds(1));
JavaDStream<String> lines = jssc.socketTextStream("localhost", 9999);
JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(x.split(" ")).iterator());
JavaPairDStream<String, Integer> pairs = words.mapToPair(s -> new Tuple2<>(s, 1));
JavaPairDStream<String, Integer> counts = pairs.reduceByKey((x, y) -> x + y);
counts.print();
jssc.start();
jssc.awaitTermination();
jssc.close();
}
private static void startSockerServer(int port) throws Exception {
new Thread(){
public void run() {
try {
ServerSocket server = new ServerSocket(port);
Socket socket = server.accept();
OutputStream os = socket.getOutputStream();
for (int i = 0; i < 1000; i++) {
String txt = UUID.randomUUID().toString().replaceAll("-", " ");
txt = "Hello test\n";
os.write(txt.getBytes());
Thread.sleep(10);
}
socket.close();
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
會不斷地打印出類似的結果:
-------------------------------------------
Time: 1490947248000 ms
-------------------------------------------
(Hello,99)
(test,99)
感謝各位的閱讀,以上就是“Spark Stream怎么使用”的內容了,經過本文的學習后,相信大家對Spark Stream怎么使用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。