在Ktor拦截器中的状态

时间:2018-10-15 09:35:50

标签: kotlin ktor

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

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

1 个答案:

答案 0 :(得分:0)

您可以在周围的封口中保留状态。我通过增加超时来扩展您的示例:

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
}