package gaf3.core.cache.util

import java.util.concurrent.ConcurrentHashMap

class MemCache<T> {
    private val items: MutableMap<String, Cache<T>> = ConcurrentHashMap()

    /**
     * 设置缓存
     * @param key 键值
     * @param data 数据对象
     * @param expired 失效时间戳（毫秒）
     */
    fun setCache(key: String, data: T, expired: Long = 0) {
        items[key] = Cache(data, expired)
    }

    fun getCache(key: String): T? {
        return items[key]?.let {
            if(it.expired > 0 && it.expired <= System.currentTimeMillis()) {
                items.remove(key)
                null
            } else {
                it.data
            }
        }
    }
    fun delCache(key: String) {
        items[key]?.let {
            items.remove(key)
        }
    }

    internal class Cache<T>(var data: T, var expired: Long)
}