com.blr19c.falowp.bot.system.cache.CacheMap.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of falowp-bot-system Show documentation
Show all versions of falowp-bot-system Show documentation
FalowpBot system infrastructure
package com.blr19c.falowp.bot.system.cache
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import kotlinx.coroutines.runBlocking
import kotlin.reflect.KProperty
import kotlin.time.Duration
import kotlin.time.toJavaDuration
/**
* 缓存
*/
class CacheMap(
duration: Duration,
private val block: suspend (K) -> V,
) {
private val cache = CacheBuilder.newBuilder()
.expireAfterWrite(duration.toJavaDuration())
.build(CacheLoader.from { key -> runBlocking { block.invoke(key) } })
operator fun getValue(thisRef: Any, property: KProperty<*>): suspend (K) -> V {
return { key: K -> cache.get(key) }
}
fun refresh(key: K) {
return cache.refresh(key)
}
fun refreshAll() {
cache.cleanUp()
}
}