查看: 36|回复: 0

[Lua] TTL缓存模块:避免频繁查询数据库拖慢服务端

[复制链接]

46

主题

42

回帖

1212

积分

金牌会员

积分
1212
发表于 2026-6-4 23:57:06 | 显示全部楼层 |阅读模式
-- Cache.lua
-- 带TTL(生存时间)的内存缓存,适合缓存玩家属性、排行榜等高频读取数据

local Cache = {}
local _store = {}  -- { key = { value, expireAt } }

-- 设置缓存,ttl 单位:秒
function Cache.set(key, value, ttl)
    _store[key] = {
        value    = value,
        expireAt = os.time() + (ttl or 60)
    }
end

-- 读取缓存,过期返回 nil
function Cache.get(key)
    local item = _store[key]
    if not item then return nil end
    if os.time() > item.expireAt then
        _store[key] = nil
        return nil
    end
    return item.value
end

-- 主动失效
function Cache.invalidate(key)
    _store[key] = nil
end

-- 清理所有过期项(建议挂到定时器,每5分钟跑一次)
function Cache.gc()
    local now = os.time()
    local count = 0
    for k, item in pairs(_store) do
        if now > item.expireAt then
            _store[k] = nil
            count = count + 1
        end
    end
    return count
end

return Cache



实战用法:
local Cache = require("Cache")function GetPlayerRank(playerName)    local cacheKey = "rank:" .. playerName    local cached = Cache.get(cacheKey)    if cached then return cached end  -- 缓存命中,直接返回    -- 缓存未命中,查数据库    local rank = DB.query("SELECT rank FROM leaderboard WHERE name=?", playerName)    Cache.set(cacheKey, rank, 30)  -- 缓存30秒    return rankend-- 玩家积分变化时主动失效function OnScoreChanged(playerName)    Cache.invalidate("rank:" .. playerName)end
性能对比: 排行榜查询从每次调用都走DB,变成30秒内只查1次,高并发场景下压力降低数十倍。

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表