Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spark和不可序列化的DateTimeFormatter_Java_Scala_Serialization_Apache Spark - Fatal编程技术网

Java Spark和不可序列化的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

我试图在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(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,这是一种很好的方法


    以下是。

    严重遗漏此序列化方面/问题。