輸出操作概覽
在Spark應用中,外部系統經常需要使用到SparkStreaming處理後的數據,因此,需要採用輸出操作把DStream的數據輸出到數據庫或者文件系統中。
Output | Meaning |
---|---|
打印每個batch中的前10個元素,主要用於測試,或者是不需要執行什麼output操作時,用於簡單觸發一下job。 | |
saveAsTextFile(prefix, [suffix]) | 將每個batch的數據保存到文件中。每個batch的文件的命名格式爲:prefix-TIME_IN_MS[.suffix] |
saveAsObjectFile | 同上,但是將每個batch的數據以序列化對象的方式,保存到SequenceFile中。 |
saveAsHadoopFile | 同上,將數據保存到Hadoop文件中 |
foreachRDD | 最常用的output操作,遍歷DStream中的每個產生的RDD,進行處理。可以將每個RDD中的數據寫入外部存儲,比如文件、數據庫、緩存等。通常在其中,是針對RDD執行action操作的,比如foreach。 |
DStream中的所有計算,都是由output操作觸發的,比如print()。如果沒有任何output操作,那麼壓根兒就不會執行定義的計算邏輯。
此外,即使你使用了foreachRDD output操作,也必須在裏面對RDD執行action操作,才能觸發對每一個batch的計算邏輯。否則,光有foreachRDD output操作,在裏面沒有對RDD執行action操作,也不會觸發任何邏輯。
foreachRDD詳解
通常在foreachRDD中,都會創建一個Connection,比如JDBC Connection,然後通過Connection將數據寫入外部存儲。
我們可以採用以下兩種方式來建立連接:
(1) 使用RDD的foreachPartition操作
使用RDD的foreachPartition操作,並且在該操作內部,創建Connection對象,這樣就相當於是,爲RDD的每個partition創建一個Connection對象,好處是節省資源。
dstream.foreachRDD { rdd =>
rdd.foreachPartition { partitionOfRecords =>
val connection = createNewConnection()
partitionOfRecords.foreach(record => connection.send(record))
connection.close()
}
}
(2) 使用連接池
封裝一個靜態連接池,使用RDD的foreachPartition操作,並且在該操作內部,從靜態連接池中,通過靜態方法,獲取到一個連接,使用之後再還回去。這樣的話,甚至在多個RDD的partition之間,也可以複用連接了。而且可以讓連接池採取懶創建的策略,並且空閒一段時間後,將其釋放掉。
這裏我就第二種方法寫一個連接MySQL數據庫的代碼實例:
- 手動實現一個靜態連接池
public class ConnectionPool {
// 靜態的Connection隊列
private static LinkedList<Connection> connectionQueue;
//加載驅動
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 獲取連接,多線程訪問併發控制
public synchronized static Connection getConnection() {
try {
if (connectionQueue == null) {
connectionQueue = new LinkedList<Connection>();
for (int i = 0; i < 10; i++) {
Connection conn = DriverManager.getConnection("jdbc:mysql://spark1:3306/testdb", "", "");
connectionQueue.push(conn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return connectionQueue.poll();
}
// 還回去一個連接
public static void returnConnection(Connection conn) {
connectionQueue.push(conn);
}
}
- foreachRDD操作實例
public class PersistWordCount {
public static void main(String[] args) {
SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("PersistWordCount");
JavaStreamingContext jssc = new JavaStreamingContext(conf, Durations.seconds(5));
// 開啓checkpoint機制
jssc.checkpoint("hdfs://spark1:9000/wordcount_checkpoint");
JavaReceiverInputDStream<String> lines = jssc.socketTextStream("spark1", 9999);
JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
private static final long serialVersionUID = 1L;
@Override
public Iterable<String> call(String line) throws Exception {
return Arrays.asList(line.split(" "));
}
});
JavaPairDStream<String, Integer> pairs = words.mapToPair(
new PairFunction<String, String, Integer>() {
private static final long serialVersionUID = 1L;
@Override
public Tuple2<String, Integer> call(String word) throws Exception {
return new Tuple2<String, Integer>(word, 1);
}
});
JavaPairDStream<String, Integer> wordCounts = pairs.updateStateByKey(
new Function2<List<Integer>, Optional<Integer>, Optional<Integer>>() {
private static final long serialVersionUID = 1L;
@Override
public Optional<Integer> call(List<Integer> values, Optional<Integer> state)
throws Exception {
Integer newValue = 0;
if (state.isPresent()) {
newValue = state.get();
}
for (Integer value : values) {
newValue += value;
}
return Optional.of(newValue);
}
});
// 每次得到當前所有單詞的統計次數之後,將其寫入mysql存儲,進行持久化,以便於後續的J2EE應用程序
// 進行顯示
wordCounts.foreachRDD(new Function<JavaPairRDD<String, Integer>, Void>() {
private static final long serialVersionUID = 1L;
@Override
public Void call(JavaPairRDD<String, Integer> wordCountsRDD) throws Exception {
// 調用RDD的foreachPartition()方法
wordCountsRDD.foreachPartition(new VoidFunction<Iterator<Tuple2<String, Integer>>>() {
private static final long serialVersionUID = 1L;
@Override
public void call(Iterator<Tuple2<String, Integer>> wordCounts) throws Exception {
// 給每個partition,獲取一個連接
Connection conn = ConnectionPool.getConnection();
// 遍歷partition中的數據,使用一個連接,插入數據庫
Tuple2<String, Integer> wordCount = null;
while (wordCounts.hasNext()) {
wordCount = wordCounts.next();
String sql = "insert into wordcount(word,count) " + "values('" + wordCount._1 + "',"
+ wordCount._2 + ")";
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
}
// 用完以後,將連接還回去
ConnectionPool.returnConnection(conn);
}
});
return null;
}
});
jssc.start();
jssc.awaitTermination();
jssc.close();
}
}
還可以scala編寫數據庫連接,主要代碼如下所示:
stateDstream.foreachRDD(rdd => {
//內部函數
def func(records: Iterator[(String,Int)]) {
var conn: Connection = null
var stmt: PreparedStatement = null
try {
val url = "jdbc:mysql://localhost:3306/spark"
val user = "root"
val password = "hadoop"
conn = DriverManager.getConnection(url, user, password)
records.foreach(p => {
val sql = "insert into wordcount(word,count) values (?,?)"
stmt = conn.prepareStatement(sql)
stmt.setString(1, p._1.trim)
stmt.setInt(2,p._2.toInt)
stmt.executeUpdate()
})
} catch {
case e: Exception => e.printStackTrace()
} finally {
if (stmt != null) {
stmt.close()
}
if (conn != null) {
conn.close()
}
}
}
val repartitionedRDD = rdd.repartition(3)
repartitionedRDD.foreachPartition(func)
})