@xtccc
2017-08-21T23:41:19.000000Z
字数 1888
阅读 1737
Scala
有一篇比较各种库性能的文章:
Scala Serialization
参考:
pickling是最方便的序列化库,可以直接支持大部分的Scala数据类型。
import scala.pickling.Defaults._
import scala.pickling.binary._
val d = new DateTime()
val pckl = d.pickle
val bytes = pckl.value // 序列化成字节
println(s"bytes length = ${bytes.length}")
val obj = BinaryPickle(bytes).unpickle[DateTime]
println(s"obj = $obj") // 从字节数组反序列化回来
先看个最基本的case class的pickler/unpickler
import scala.pickling.tags.FastTypeTag
import scala.pickling.binary._
import scala.pickling.Defaults._
import scala.pickling._
case class Foo(val x: String, y: Int, z: String)
object CustomerPicklerUnpicklers {
implicit object FooPickler extends AbstractPicklerUnpickler[Foo] {
// 不需要写 stringPickler,写了的话会报错, 以为已经存在PrimitivePicklers.stringPickler
val stringUnpickler = implicitly[Unpickler[String]] // 但是不存在stringUnpickler
val intUnpickler = implicitly[Unpickler[Int]]
override val tag = FastTypeTag[Foo]
override def pickle(foo: Foo, builder: PBuilder): Unit = {
println(s"Pickling Foo ...")
builder.beginEntry(foo, tag)
builder.putField("x", b => stringPickler.pickle(foo.x , b))
builder.putField("y", b => intPickler.pickle(foo.y , b))
builder.putField("z", b => stringPickler.pickle(foo.z , b))
builder.endEntry()
}
override def unpickle(tag: String, reader: PReader): Foo = {
println("Unpickling Foo ...")
val x = stringUnpickler.unpickleEntry(reader.readField("x")).asInstanceOf[String]
val y = intUnpickler.unpickleEntry(reader.readField("y")).asInstanceOf[Int]
val z = stringUnpickler.unpickleEntry(reader.readField("z")).asInstanceOf[String]
Foo(x, y, z)
}
}
}
object TestFoo {
import CustomerPicklerUnpicklers._
def main(args: Array[String]): Unit = {
val foo = Foo("Hello", 100, null) // 支持null
val pckl = foo.pickle
val bytes = pckl.value
println(s"length = ${bytes.length}")
val obj = BinaryPickle(bytes).unpickle[Foo]
println(obj)
}
}
输出为
Pickling Foo ...
length = 79
Unpickling Foo ...
Foo(Hello,100,null)