我想将我的缓存配置Caffeine
为在加载程序无法刷新缓存时返回陈旧的结果。以下 Kotlin 代码演示了这种情况:
@Test
fun `completeble future`() = runBlocking {
val cache = Caffeine.newBuilder()
.refreshAfterWrite(Duration.ofSeconds(1))
.expireAfterWrite(Duration.ofSeconds(1))
.buildAsync<String, String> { key: String, executor ->
GlobalScope.future(executor.asCoroutineDispatcher()) {
throw Exception("== Error ==")
}
}
cache.put("id", CompletableFuture.completedFuture("value"))
delay(2000)
assertEquals("value", cache.get("id").await())
}
我希望此测试能够通过,但我收到以下错误:
WARNING: Exception thrown during asynchronous load
java.lang.Exception: == Error ==
at fsra.manager.TranslationManagerImplTest$completeble future$1$cache$1$1.invokeSuspend(TranslationManagerImplTest.kt:93)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1426)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)
java.lang.Exception: == Error ==
at fsra.manager.TranslationManagerImplTest$completeble future$1$cache$1$1.invokeSuspend(TranslationManagerImplTest.kt:93)
at |b|b|b(Coroutine boundary.|b(|b)
at fsra.manager.TranslationManagerImplTest$completeble future$1.invokeSuspend(TranslationManagerImplTest.kt:101)
Caused by: java.lang.Exception: == Error ==
at fsra.manager.TranslationManagerImplTest$completeble future$1$cache$1$1.invokeSuspend(TranslationManagerImplTest.kt:93)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1426)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177)
我在 Kotlin 中编写了代码,但我认为这个问题与 Kotlin 协程无关。我想将 Caffeine 配置为在刷新时不抛出,而是在缓存中返回之前的结果。