Apache Fory™ 使用
本章节演示不同编程语言使用 Apache Fory™ 进行序列化。
Java 序列化
import java.util.List;
import java.util.Arrays;
import io.fory.*;
public class Example {
public static void main(String[] args) {
SomeClass object = new SomeClass();
// Note that Fory instances should be reused between
// multiple serializations of different objects.
Fory fory = Fory.builder().withLanguage(Language.JAVA)
// Allow to deserialize objects unknown types,
// more flexible but less secure.
// .requireClassRegistration(false)
.build();
// Registering types can reduce class name serialization overhead, but not mandatory.
// If secure mode enabled, all custom types must be registered.
fory.register(SomeClass.class);
byte[] bytes = fory.serialize(object);
System.out.println(fory.deserialize(bytes));
}
}
Scala序列化
import org.apache.fory.Fory
import org.apache.fory.serializer.scala.ScalaSerializers
case class Person(name: String, id: Long, github: String)
case class Point(x : Int, y : Int, z : Int)
object ScalaExample {
val fory: Fory = Fory.builder().withScalaOptimizationEnabled(true).build()
// Register optimized fory serializers for scala
ScalaSerializers.registerSerializers(fory)
fory.register(classOf[Person])
fory.register(classOf[Point])
def main(args: Array[String]): Unit = {
val p = Person("Shawn Yang", 1, "https://github.com/chaokunyang")
println(fory.deserialize(fory.serialize(p)))
println(fory.deserialize(fory.serialize(Point(1, 2, 3))))
}
}
## Kotlin序列化
```kotlin
import org.apache.fory.Fory
import org.apache.fory.ThreadSafeFory
import org.apache.fory.serializer.kotlin.KotlinSerializers
data class Person(val name: String, val id: Long, val github: String)
data class Point(val x : Int, val y : Int, val z : Int)
fun main(args: Array<String>) {
// 注意: 下面的Fory初始化代码应该只执行一次,而不是在每次序列化前都运行
val fory: ThreadSafeFory = Fory.builder().requireClassRegistration(true).buildThreadSafeFory()
KotlinSerializers.registerSerializers(fory)
fory.register(Person::class.java)
fory.register(Point::class.java)
val p = Person("Shawn Yang", 1, "https://github.com/chaokunyang")
println(fory.deserialize(fory.serialize(p)))
println(fory.deserialize(fory.serialize(Point(1, 2, 3))))
}