0

我正在遵循此帮助页面上的说明: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
}

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

4

1 回答 1

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
}
于 2018-10-17T19:21:19.280 回答