Java Spark和不可序列化的DateTimeFormatter
我试图在Spark中使用java.time.format中的DateTimeFormatter,但它似乎不可序列化。这是相关的代码块:Java Spark和不可序列化的DateTimeFormatter,java,scala,serialization,apache-spark,Java,Scala,Serialization,Apache Spark,我试图在Spark中使用java.time.format中的DateTimeFormatter,但它似乎不可序列化。这是相关的代码块: val pattern = "<some pattern>".r val dtFormatter = DateTimeFormatter.ofPattern("<some non-ISO pattern>") val logs = sc.wholeTextFiles(path) val entries = logs.flatMap(f
val pattern = "<some pattern>".r
val dtFormatter = DateTimeFormatter.ofPattern("<some non-ISO pattern>")
val logs = sc.wholeTextFiles(path)
val entries = logs.flatMap(fileContent => {
val file = fileContent._1
val content = fileContent._2
content.split("\\r?\\n").map(line => line match {
case pattern(dt, ev, seq) => Some(LogEntry(LocalDateTime.parse(dt, dtFormatter), ev, seq.toInt))
case _ => logger.error(s"Cannot parse $file: $line"); None
})
})
val pattern=”“.r
val dtFormatter=DateTimeFormatter.of模式(“”)
val logs=sc.wholeTextFiles(路径)
val entries=logs.flatMap(fileContent=>{
val file=fileContent.\u 1
val content=fileContent.\u 2
content.split(“\\r?\\n”).map(行=>行匹配{
案例模式(dt,ev,seq)=>Some(LogEntry(LocalDateTime.parse(dt,dtFormatter),ev,seq.toInt))
case=>logger.error“无法解析$file:$line”);无
})
})
如何避免
java.io.NotSerializableException:java.time.format.DateTimeFormatter
异常?是否有更好的库来解析时间戳?我已经读到Joda也是不可序列化的,并且已经被合并到Java 8的时间库中。可以通过两种方式避免序列化:
对象中(使其为“静态”)。这意味着可以在每个worker中访问静态值,而不是驱动程序序列化它并发送给worker:
object MyUtils {
val dtFormatter = DateTimeFormatter.ofPattern("<some non-ISO pattern>")
}
import MyUtils._
logs.flatMap(fileContent => {
// can safely use formatter here
})
对象MyUtils{
val dtFormatter=DateTimeFormatter.of模式(“”)
}
导入MyUtils_
logs.flatMap(fileContent=>{
//可以在这里安全地使用格式化程序
})
logs.flatMap(fileContent => {
val dtFormatter = DateTimeFormatter.ofPattern("<some non-ISO pattern>")
// use formatter here
})
logs.flatMap(fileContent=>{
val dtFormatter=DateTimeFormatter.of模式(“”)
//在这里使用格式化程序
})
另一种方法是使DateTimeFormatter暂时化。这告诉JVM/Spark不序列化变量,而是从头开始构造。对于每个执行器构造的东西,比如DateTimeFormatter,这是一种很好的方法
以下是。严重遗漏此序列化方面/问题。