【问题标题】:State in Ktor InterceptersKtor 拦截器中的状态
【发布时间】:2018-10-15 09:35:49
【问题描述】:

我正在按照此帮助页面上的说明进行操作:https://ktor.io/advanced/pipeline/route.html

他们举了这个例子:

fun Route.routeTimeout(time: Long, unit: TimeUnit = TimeUnit.SECONDS, callback: Route.() -> Unit): Route {
    // With createChild, we create a child node for this received Route  
    val routeWithTimeout = this.createChild(object : RouteSelector(1.0) {
        override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation =
            RouteSelectorEvaluation.Constant
    })

    // Intercepts calls from this route at the features step
    routeWithTimeout.intercept(ApplicationCallPipeline.Features) {
        withTimeout(time, unit) {
            proceed() // With proceed we can define code to be executed before and after the call
        }
    }

    // Configure this route with the block provided by the user
    callback(routeWithTimeout)

    return routeWithTimeout
}

我想修改它,以便它可以保持状态。例如,每个下一个调用者都会获得更大的超时。我在哪里放置我的状态?

【问题讨论】:

    标签: kotlin ktor


    【解决方案1】:

    您可以将状态保持在周围的闭包中。我通过增加超时来扩展您的示例:

    fun Route.routeTimeout(time: Long, unit: TimeUnit = TimeUnit.SECONDS, callback: Route.() -> Unit): Route {
        // With createChild, we create a child node for this received Route
        val routeWithTimeout = this.createChild(object : RouteSelector(1.0) {
            override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation =
                RouteSelectorEvaluation.Constant
        })
    
        // state
        var newTime = time
    
        // Intercepts calls from this route at the features step
        routeWithTimeout.intercept(ApplicationCallPipeline.Features) {
            try{
                withTimeout(newTime, unit) {
                    proceed() // With proceed we can define code to be executed before and after the call
                }
            } catch (e: TimeoutCancellationException) {
                // change the state
                newTime*=2
                throw e
            }
        }
    
        // Configure this route with the block provided by the user
        callback(routeWithTimeout)
    
        return routeWithTimeout
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-22
      • 1970-01-01
      • 2019-10-20
      • 2019-09-08
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2017-10-03
      相关资源
      最近更新 更多