【问题标题】:Redis script for memory flush用于内存刷新的 Redis 脚本
【发布时间】:2020-02-17 16:41:53
【问题描述】:

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

【问题讨论】:

  • 这能回答你的问题吗? Abuse cURL to communicate with Redis
  • 这没有回答我。也许要了解更多信息,我正在使用 GCP Memorystore
  • 如果我使用(printf "MEMORY STATS\r\n";) | nc REDIS_IP 6379,我将获得所有值。有没有办法只看到一个字段?我正在寻找类似grep
  • 也许这个命令比第一个更有用redis-cli -h REDIS_IP -p 6379 memory stats

标签: redis


【解决方案1】:

我会使用 Lua 脚本,因为它的执行速度更快、原子性更强,而且在 redis-cli 和任何应用程序代码中都很容易使用。

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

MEMORY STATS 带来结构化信息,但不像INFO memory 那样包含maxmemorytotal_system_memory。 Lua 脚本中不允许使用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"

【讨论】:

    【解决方案2】:

    这就是获得分配内存redis-cli -h 1.2.3.4 -p 6379 memory stats | sed -n 4p的方法。现在很容易创建一个 bash 脚本

    【讨论】:

      猜你喜欢
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-11
      • 1970-01-01
      • 2015-10-01
      • 2014-02-14
      • 2010-10-17
      相关资源
      最近更新 更多