Skip to content

Commit

Permalink
MemoryCache 优化
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaojinzi123 committed Mar 20, 2024
1 parent 62356ee commit e1f8bc1
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions lib-ktx/src/main/java/com/xiaojinzi/support/ktx/MemoryCache.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,37 @@ object MemoryCache {
configMap[keyClass.hashCode()] = config
}

/**
* 获取当前时间的数据, 过期了会触发更新
*/
@Suppress("UNCHECKED_CAST")
fun <T, Key : MemoryCacheKey> get(key: Key): T? {
val configKey = key::class.hashCode()
val dataKey = "${configKey}@${key.hashCode()}"
val targetConfig: MemoryCacheConfig<Key> =
(configMap[configKey]
?: notSupportError(message = "not found config for key: $key")) as MemoryCacheConfig<Key>
val expiredTime = dataMap[dataKey]?.first ?: 0
// 如果过期, 执行一次更新
if (expiredTime <= System.currentTimeMillis()) {
// 如果过期了
LogSupport.d(
tag = TAG,
content = "key $key is expired, update it, configKey = $configKey, dataKey = $dataKey",
)
executeTaskInCoroutinesIgnoreError {
dataMap[dataKey] =
(System.currentTimeMillis() +
targetConfig.cacheTime) to targetConfig
.updateCallable(key)
flow.emit(
value = dataMap,
)
}
}
return dataMap[dataKey]?.second as? T
}

/**
* 订阅数据
*/
Expand All @@ -51,6 +82,7 @@ object MemoryCache {
(configMap[configKey]
?: notSupportError(message = "not found config for key: $key")) as MemoryCacheConfig<Key>
val expiredTime = dataMap[dataKey]?.first ?: 0
// 如果过期, 执行一次更新
if (expiredTime <= System.currentTimeMillis()) {
// 如果过期了
LogSupport.d(
Expand All @@ -59,10 +91,9 @@ object MemoryCache {
)
executeTaskInCoroutinesIgnoreError {
dataMap[dataKey] =
(System.currentTimeMillis() + targetConfig.cacheTime) to
targetConfig.updateCallable(
key
)
(System.currentTimeMillis() +
targetConfig.cacheTime) to targetConfig
.updateCallable(key)
flow.emit(
value = dataMap,
)
Expand Down

0 comments on commit e1f8bc1

Please sign in to comment.