From 4c83e00bf8904ea291b57a9a93b9a760548606fb Mon Sep 17 00:00:00 2001 From: Xwite <1797350009@qq.com> Date: Wed, 4 May 2022 17:04:11 +0800 Subject: [PATCH] =?UTF-8?q?feat(CacheManager):=E6=B7=BB=E5=8A=A0=E5=86=85?= =?UTF-8?q?=E5=AD=98=E7=BC=93=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/io/legado/app/help/CacheManager.kt | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/io/legado/app/help/CacheManager.kt b/app/src/main/java/io/legado/app/help/CacheManager.kt index 606248559..156b16998 100644 --- a/app/src/main/java/io/legado/app/help/CacheManager.kt +++ b/app/src/main/java/io/legado/app/help/CacheManager.kt @@ -1,5 +1,6 @@ package io.legado.app.help +import androidx.collection.LruCache import io.legado.app.data.appDb import io.legado.app.data.entities.Cache import io.legado.app.model.analyzeRule.QueryTTF @@ -10,6 +11,11 @@ import splitties.init.appCtx object CacheManager { private val queryTTFMap = hashMapOf>() + private val memoryLruCache = object : LruCache(100) { + override fun sizeOf(key: String, value: Cache): Int { + return 1 + } + } /** * saveTime 单位为秒 @@ -23,13 +29,26 @@ object CacheManager { is ByteArray -> ACache.get(appCtx).put(key, value, saveTime) else -> { val cache = Cache(key, value.toString(), deadline) + memoryLruCache.put(key, cache) appDb.cacheDao.insert(cache) } } } fun get(key: String): String? { - return appDb.cacheDao.get(key, System.currentTimeMillis()) + return getFromMemory(key) ?: appDb.cacheDao.get(key, System.currentTimeMillis()) + } + + //从内存中获取数据 使用lrucache 支持过期功能 + private fun getFromMemory(key: String): String? { + val cache = memoryLruCache.get(key) ?: return null + val deadline = cache!!.deadline + return if (deadline == 0L || deadline > System.currentTimeMillis()) { + cache!!.value + } else { + memoryLruCache.remove(key) + null + } } fun getInt(key: String): Int? { @@ -70,6 +89,7 @@ object CacheManager { fun delete(key: String) { appDb.cacheDao.delete(key) + memoryLruCache.remove(key) ACache.get(appCtx).remove(key) } } \ No newline at end of file