我正在尝试使用 Spark 处理来自 HBase 表的数据。这篇博文 http://www.vidyasource.com/blog/Programming/Scala/Java/Data/Hadoop/Analytics/2014/01/25/lighting-a-spark-with-hbase给出了如何使用的示例NewHadoopAPI
从任何 Hadoop 读取数据InputFormat
.
我做了什么
由于我需要多次执行此操作,因此我尝试使用隐式来丰富SparkContext
,这样我就可以从 HBase 中给定的一组列中获取 RDD。我编写了以下帮助程序:
trait HBaseReadSupport {
implicit def toHBaseSC(sc: SparkContext) = new HBaseSC(sc)
implicit def bytes2string(bytes: Array[Byte]) = new String(bytes)
}
final class HBaseSC(sc: SparkContext) extends Serializable {
def extract[A](data: Map[String, List[String]], result: Result, interpret: Array[Byte] => A) =
data map { case (cf, columns) =>
val content = columns map { column =>
val cell = result.getColumnLatestCell(cf.getBytes, column.getBytes)
column -> interpret(CellUtil.cloneValue(cell))
} toMap
cf -> content
}
def makeConf(table: String) = {
val conf = HBaseConfiguration.create()
conf.setBoolean("hbase.cluster.distributed", true)
conf.setInt("hbase.client.scanner.caching", 10000)
conf.set(TableInputFormat.INPUT_TABLE, table)
conf
}
def hbase[A](table: String, data: Map[String, List[String]])
(interpret: Array[Byte] => A) =
sc.newAPIHadoopRDD(makeConf(table), classOf[TableInputFormat],
classOf[ImmutableBytesWritable], classOf[Result]) map { case (key, row) =>
Bytes.toString(key.get) -> extract(data, row, interpret)
}
}
它可以像这样使用
val rdd = sc.hbase[String](table, Map(
"cf" -> List("col1", "col2")
))
在这种情况下,我们得到的 RDD 为(String, Map[String, Map[String, String]])
,其中第一个组件是行键,第二个组件是一个映射,其键是列族,值是键是列、内容是单元格值的映射。
失败的地方
不幸的是,我的工作似乎得到了参考sc
,它本身在设计上是不可序列化的。当我运行工作时我得到的是
Exception in thread "main" org.apache.spark.SparkException: Job aborted: Task not serializable: java.io.NotSerializableException: org.apache.spark.SparkContext
at org.apache.spark.scheduler.DAGScheduler$$anonfun$org$apache$spark$scheduler$DAGScheduler$$abortStage$1.apply(DAGScheduler.scala:1028)
我可以删除辅助类并在工作中使用相同的内联逻辑,一切都运行良好。但我想要得到一些可以重用的东西,而不是一遍又一遍地编写相同的样板。
顺便说一句,这个问题并不特定于隐式,即使使用函数sc
表现出同样的问题。
为了进行比较,以下读取 TSV 文件的帮助程序(我知道它已损坏,因为它不支持引用等,没关系)似乎工作正常:
trait TsvReadSupport {
implicit def toTsvRDD(sc: SparkContext) = new TsvRDD(sc)
}
final class TsvRDD(val sc: SparkContext) extends Serializable {
def tsv(path: String, fields: Seq[String], separator: Char = '\t') = sc.textFile(path) map { line =>
val contents = line.split(separator).toList
(fields, contents).zipped.toMap
}
}
如何封装从 HBase 读取行的逻辑,而不会无意中捕获 SparkContext?