首页 > 解决方案 > 用于内存刷新的 Redis 脚本

问题描述

是否可以为 Redis 创建一个脚本,当它高于某个值时刷新它的内存?在我的具体情况下,我想要在内存高于 90% 时刷新。最好的方法是什么,通过 bash 脚本或 Lua 脚本?

标签: redis

解决方案


我会使用 Lua 脚本,因为它会以原子方式更快地执行,并且在 redis-cli 和任何应用程序代码中都很容易使用。

这里有一个 Lua 脚本,用于获取已使用maxmemory的内存、百分比和操作占位符。它同时使用MEMORY STATSINFO memory来说明。

MEMORY STATS带来结构化信息,但不包括maxmemoryor 。不允许在 Lua 脚本中使用。total_system_memoryINFO memoryCONFIG GET

local stats = redis.call('MEMORY', 'STATS')
local memused = 0
for i = 1,table.getn(stats),2 do
    if stats[i] == 'total.allocated' then
        memused = stats[i+1]
        break
    end
end
local meminfo = redis.call('INFO', 'memory')
local maxmemory = 0
for s in meminfo:gmatch('[^\\r\\n]+') do
    if string.sub(s,1,10) == 'maxmemory:' then
        maxmemory = tonumber(string.sub(s,11))
    end
end
local mempercent = memused/maxmemory
local action = 'No action'
if mempercent > tonumber(ARGV[1]) then
    action = 'Flush here'
end
return {memused, maxmemory, tostring(mempercent), action}

用于:

> EVAL "local stats = redis.call('MEMORY', 'STATS') \n local memused = 0 \n for i = 1,table.getn(stats),2 do \n     if stats[i] == 'total.allocated' then \n     memused = stats[i+1] \n break \n end \n end \n local meminfo = redis.call('INFO', 'memory') \n local maxmemory = 0 \n for s in meminfo:gmatch('[^\\r\\n]+') do \n     if string.sub(s,1,10) == 'maxmemory:' then \n     maxmemory = tonumber(string.sub(s,11)) \n end \n end \n local mempercent = memused/maxmemory \n local action = 'No action' \n if mempercent > tonumber(ARGV[1]) then \n     action = 'Flush here' \n end \n return {memused, maxmemory, tostring(mempercent), action}" 0 0.9
1) (integer) 860264
2) (integer) 100000000
3) "0.00860264"
4) "No action"

推荐阅读