Штат в ктор перехватчики - PullRequest
       8

Штат в ктор перехватчики

0 голосов
/ 15 октября 2018

Я следую инструкциям на этой странице справки: 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 голосов
/ 17 октября 2018

Вы можете удерживать состояние в окружающем закрытии.Я расширил ваш пример с увеличением времени ожидания:

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
}
...