Kotlin Ktor拦截器中的状态
我在此帮助页面上遵循以下说明: 他们举了一个例子:Kotlin Ktor拦截器中的状态,kotlin,ktor,Kotlin,Ktor,我在此帮助页面上遵循以下说明: 他们举了一个例子: 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.createCh
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
}
我想修改它,以便它可以保持状态。例如,每个下一个调用方都会获得更大的超时。我应该把我的状态放在哪里?你可以将状态保存在周围的闭包中。我通过增加超时扩展了您的示例:
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
}