配置
本页介绍 Kotlin 专属运行时配置和 Fory 实例创建。
Xlang 设置
Fory Kotlin 遵循 Java builder 默认值:启用 xlang 模式和兼容 Schema 演进。 跨语言 Kotlin 载荷、Schema IDL 生成的 Kotlin 模型,以及 KSP 生成的 xlang 序列化器都应使用这条路径。
import org.apache.fory.kotlin.ForyKotlin
val fory = ForyKotlin.builder()
.withXlang(true)
.requireClassRegistration(true)
.build()
Native 模式设置
对于需要原生 JVM 对象行为的同语言 Kotlin/JVM 载荷,请显式使用 native 模式:
import org.apache.fory.kotlin.ForyKotlin
val fory = ForyKotlin.builder().withXlang(false)
.requireClassRegistration(true)
.build()
线程安全
创建 Fory 实例成本不低。实例应在多次序列化之间共享。
单线程用法
import org.apache.fory.Fory
import org.apache.fory.kotlin.ForyKotlin
object ForyHolder {
val fory: Fory = ForyKotlin.builder()
.withXlang(true)
.requireClassRegistration(true)
.build()
}
多线程用法
对于多线程应用,请使用 ThreadSafeFory:
import org.apache.fory.ThreadSafeFory
import org.apache.fory.kotlin.ForyKotlin
object ForyHolder {
val fory: ThreadSafeFory = ForyKotlin.builder()
.withXlang(true)
.requireClassRegistration(true)
.buildThreadSafeFory()
}
使用 Builder 方法
// Thread-safe Fory
val fory: ThreadSafeFory = ForyKotlin.builder()
.withXlang(true)
.requireClassRegistration(true)
.buildThreadSafeFory()
配置
Fory Java 的所有配置选项都可用。完整列表请参见 Java 配置。
Kotlin native 模式载荷的常见选项:
import org.apache.fory.kotlin.ForyKotlin
val fory = ForyKotlin.builder().withXlang(false)
// Enable reference tracking for circular references
.withRefTracking(true)
// Enable schema evolution support for native-mode payloads
.withCompatible(true)
// Bound remote schema metadata resource usage
.withMaxTypeFields(512)
.withMaxTypeMetaBytes(4096)
// Enable async compilation for better startup performance
.withAsyncCompilation(true)
// Compression options
.withIntCompressed(true)
.withLongCompressed(true)
.build()
安全
生产环境以及任何不受信任的 payload 来源都应保持启用类注册:
val fory = ForyKotlin.builder()
.requireClassRegistration(true)
.withMaxDepth(50)
.withMaxTypeFields(512)
.withMaxTypeMetaBytes(4096)
.build()
安全相关配置:
- 保持
requireClassRegistration(true),并注册应用类或生成的 module。 - 使用
withMaxDepth(...)拒绝异常深的对象图。 - 除非数据不是恶意输入,且可信 peer 会发送更大的 metadata 或大量 schema 版本,否则保持
withMaxTypeFields(...)、withMaxTypeMetaBytes(...)以及远端 schema-version 限制的默认值。 - Allow-listing 和 unknown-class 控制请遵循 Java 配置。