redis - 用于内存刷新的 Redis 脚本
问题描述
是否可以为 Redis 创建一个脚本,当它高于某个值时刷新它的内存?在我的具体情况下,我想要在内存高于 90% 时刷新。最好的方法是什么,通过 bash 脚本或 Lua 脚本?
解决方案
我会使用 Lua 脚本,因为它会以原子方式更快地执行,并且在 redis-cli 和任何应用程序代码中都很容易使用。
这里有一个 Lua 脚本,用于获取已使用maxmemory
的内存、百分比和操作占位符。它同时使用MEMORY STATS
和INFO memory
来说明。
MEMORY STATS
带来结构化信息,但不包括maxmemory
or 。不允许在 Lua 脚本中使用。total_system_memory
INFO memory
CONFIG 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"
推荐阅读
- java - 当edittext为空并点击按钮时Android崩溃
- javascript - Javascript。我正在尝试使用 .findIndex() 但我收到以下消息: TypeError: a is not a function
- security - OAuthV2 应用程序如何保护来自授权服务器的回调免受重放攻击?
- azure - az 角色分配在哪里列出
- list - 随机显示列表的对象,但在 Kotlin 中每个对象仅显示一次?
- .net-core - Identity Server 4 + Angular SPA 作为外部提供商的联合网关
- swiftui - 为什么我的按钮只能在选定区域点击?
- async-await - 访问 Axios 之外的数据等待获取?
- codeigniter - 主页未加载。登录后重定向到登录而不是主页
- javascript - React - 等待页面加载的正确方法?