Creating Custom Feature

预计阅读时间:2分钟

您可以开发自己的功能,并在所有Ktor应用程序中重复使用它们,也可以与社区共享它们. 典型功能具有以下结构:

class CustomFeature(configuration: Configuration) {
    val prop = configuration.prop // Copies a snapshot of the mutable config into an immutable property.
    
    class Configuration {
       var prop = "value" // Mutable property.
    }

    // Implements ApplicationFeature as a companion object.
    companion object Feature : ApplicationFeature<ApplicationCallPipeline, CustomFeature.Configuration, CustomFeature> {
       // Creates a unique key for the feature.
       override val key = AttributeKey<CustomFeature>("CustomFeature")
       
       // Code to execute when installing the feature.
       override fun install(pipeline: ApplicationCallPipeline, configure: Configuration.() -> Unit): CustomFeature {
           
           // It is responsibility of the install code to call the `configure` method with the mutable configuration.
           val configuration = CustomFeature.Configuration().apply(configure)
           
           // Create the feature, providing the mutable configuration so the feature reads it keeping an immutable copy of the properties. 
           val feature = CustomFeature(configuration)
           
           // Intercept a pipeline.
           pipeline.intercept() { 
                // Perform things in that interception point.
           }
           return feature
       }
    }
}

CustomFeature是一个功能实例类,应保持不变,以避免在高度并发的环境中产生意外的副作用. 功能实现应该是线程安全的,因为它将从多个线程中调用.

Configuration实例将交给用户安装脚本,以允许通常包含可变属性和配置方法的功能配置.

Feature随行对象符合ApplicationFeature接口,并充当胶水来构造具有正确Configuration的实际CustomFeature .

可以使用标准install功能正常安装自定义功能:

fun Application.main() {
    install(CustomFeature) { // Install a custom feature
        prop = "Hello" // configuration script
    }
}

请参阅自定义功能示例中的完整示例 .

by  ICOPY.SITE