SparkCore文件中数据的读取和保存
从文件中读取数据是创建 RDD 的一种方式.
把数据保存的文件中的操作是一种 Action.
Spark 的数据读取及数据保存可以从两个维度来作区分:文件格式以及文件系统。
文件格式分为:Text文件、Json文件、csv文件、Sequence文件以及Object文件;
文件系统分为:本地文件系统、HDFS、Hbase 以及 数据库。
平时用的比较多的就是: 从 HDFS 读取和保存 Text 文件.
1.1 读写 Text 到hdfs中文件
object textFile { def main(args: Array[String]): Unit = { //读取hdfs中的文件需要加这个,还需要将core-site.xml 放在resources中 System.setProperty("HADOOP_USER_NAME","xingmeng") val conf = new SparkConf().setAppName("textFile") .setMaster("local[2]") val sc = new SparkContext(conf) val a = "hello world" :: "hello" :: Nil sc.parallelize(a ) .flatMap(_.split("\\W+")) .map((_,1)) .reduceByKey(_+_) .saveAsTextFile("/word1016") sc.stop() } }
1.2 写入 jdbc中 的文件
object JDBCWrite { def main(args: Array[String]): Unit = { val conf = new SparkConf().setMaster("local[4]").setAppName("MapPartitionsWithIndex") val sc = new SparkContext(conf) val url = "jdbc:mysql://192.168.157.100:3306/test" val user = "root" val password = "123456" //1、加载驱动 建立连接 Class.forName("com.mysql.jdbc.Driver") val conn = DriverManager.getConnection(url, user, password) val rdd = sc.parallelize((20, "zs") :: (30, "ww") :: (61, "wl") :: Nil) Class.forName("com.mysql.jdbc.Driver") val sql = "insert into student values(?,?)" /*rdd.foreach{ case (age, name) => { val conn = DriverManager.getConnection(url, user, password) val ps = conn.prepareStatement(sql) ps.setInt(1,age) ps.setString(2,name) ps.execute() ps.close() conn.close() } }*/ //应该每个分区建立一个到mysql的连接 /* rdd.foreachPartition(it => { Class.forName("com.mysql.jdbc.Driver") val conn = DriverManager.getConnection(url, user, password) //一个元素写一次,效率不够高 it.foreach { case (age, name) => { val ps = conn.prepareStatement(sql) ps.setInt(1, age) ps.setString(2, name) ps.execute() ps.close() } conn.close() } })*/ rdd.foreachPartition(it => { Class.forName("com.mysql.jdbc.Driver") val conn = DriverManager.getConnection(url, user, password) //一次写一个批次 val ps = conn.prepareStatement(sql) var count = 0 it.foreach { case (age, name) => ps.setInt(1, age) ps.setString(2, name) ps.addBatch() count += 1 if(count % 100 == 0){ ps.executeBatch() } } //必须要有 ps.executeBatch() conn.close() conn.close() }) sc.stop() } }
1.3 读入 jdbc中 的文件
object DBCRead { def main(args: Array[String]): Unit = { val conf = new SparkConf().setMaster("local[4]").setAppName("MapPartitionsWithIndex") val sc = new SparkContext(conf) val url = "jdbc:mysql://hadoop103:3306/test" val user = "root" val password = "123456" val rdd = new JdbcRDD[String]( sc, () => { //建立到mysql的连接 //1、加载驱动 Class.forName("com.mysql.jdbc.Driver") DriverManager.getConnection(url,user,password) }, "select * from student where id >= ? and id <= ?",
1, //第一个占位符的最小值
10, //第二个占位符的最大值
2, //分区数量
(rowSet:ResultSet) => rowSet.getString(2)
)
rdd.collect.foreach(println)
sc.stop()
}
}
1.4 读写入 hbase中 的文件
object HbaseRead { def main(args: Array[String]): Unit = { val conf = new SparkConf().setMaster("local[4]").setAppName("HbaseRead") val sc = new SparkContext(conf) //连接hbase的配置 val hbaseConf = HBaseConfiguration.create() hbaseConf.set("hbase.zookeeper.quorum", "hadoop102,hadoop103,hadoop104") hbaseConf.set(TableInputFormat.INPUT_TABLE, "student") val rdd1 = sc.newAPIHadoopRDD( hbaseConf, classOf[TableInputFormat], classOf[ImmutableBytesWritable], // rowKey封装在这个类型中 classOf[Result] ) // 读到数据封装下 val resultRDD = rdd1.map { // iw只封装rowKey result封装一行数据 case (iw, result) => { val map = mutable.Map[String, Any]() // 把rowKey存入到map中 map += "rowKew" -> Bytes.toString(iw.get()) // 再把每一列也存入到map中 val cells: util.List[Cell] = result.listCells() import scala.collection.JavaConversions._ for (cell <- cells) { // 列名->列值 val key = Bytes.toString(CellUtil.cloneQualifier(cell)) val value = Bytes.toString(CellUtil.cloneValue(cell)) map += key -> value } // 把map转成json json4s(json4scala) implicit val df = org.json4s.DefaultFormats Serialization.write(map) } } resultRDD.collect.foreach(println) sc.stop() } }
读写入 hbase中 的文件
object HbaseWrite {
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setMaster("local[4]").setAppName("HbaseRead")
val sc = new SparkContext(conf)
//连接hbase的配置
val hbaseConf = HBaseConfiguration.create()
hbaseConf.set("hbase.zookeeper.quorum", "hadoop102,hadoop103,hadoop104")
hbaseConf.set(TableOutputFormat.OUTPUT_TABLE, "student")
val job = Job.getInstance(hbaseConf)
job.setOutputFormatClass(classOf[TableOutputFormat[ImmutableBytesWritable]])
job.setOutputKeyClass(classOf[ImmutableBytesWritable])
job.setOutputValueClass(classOf[Put])
val initialRDD = sc.parallelize(
List(
("10000", "apple", "11"),
("10000", "banana", "12"),
("10000", "pear", "13")
)
)
//先把rdd数据封装成 TableReduce需要的那种格式
val hbaseRDD = initialRDD.map {
//共有头14个,腿38条
case (rk, name, age) => {
val rowKey = new ImmutableBytesWritable()
rowKey.set(Bytes.toBytes(rk))
val put = new Put(Bytes.toBytes(rk))
put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("name"), Bytes.toBytes(name))
put.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("age"), Bytes.toBytes(name))
(rowKey, put)
}
}
hbaseRDD.saveAsNewAPIHadoopDataset(job.getConfiguration)
sc.stop()
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?