tibaiwan1888 发表于 2026-6-4 23:57:06

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

-- Cache.lua
-- 带TTL(生存时间)的内存缓存,适合缓存玩家属性、排行榜等高频读取数据

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

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

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

-- 主动失效
function Cache.invalidate(key)
    _store = 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 = 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次,高并发场景下压力降低数十倍。
页: [1]
查看完整版本: TTL缓存模块:避免频繁查询数据库拖慢服务端