Kotlin内本地缓存拓展方法

import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.TimeUnit

data class CacheItem<T>(val value: T, val expireAt: Long)
val localCache = ConcurrentHashMap<String, CacheItem<Any>>()

/**
 * 一个通用的本地缓存获取数据的扩展方法。
 * @param key 缓存键。
 * @param expireAfterMillis 缓存项的有效期(毫秒),默认值为1小时。
 * @param fetcher 在缓存未命中或数据过期时用于获取新数据的lambda表达式。
 * @return 缓存或新获取的数据。
 */
inline fun <reified T> getFromCacheOrFetch(
    key: String,
    expireAfterMillis: Long = TimeUnit.HOURS.toMillis(1), // 设置默认的过期时间为1小时
    fetcher: () -> T?
): T? {
    val now = System.currentTimeMillis()
    val cacheItem = localCache[key]

    if (cacheItem != null && now < cacheItem.expireAt && cacheItem.value is T) {
        return cacheItem.value as T
    } else {
        val newValue = fetcher()
        if (newValue != null) {
            localCache[key] = CacheItem(newValue as Any, now + expireAfterMillis)
        }
        return newValue
    }
}

使用方法

    fun getRandomDeviceProfile(expireAfterMillis: Long = TimeUnit.MINUTES.toMillis(10)): String? {
        val key="XHS:DeviceProfileList"
        val randomResult=getFromCacheOrFetch(key, expireAfterMillis) {
            // 这里是你的数据获取逻辑
            getAllListValues(key)
        }
        return randomResult?.randomOne()
    }