欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Redis使用LUA脚本计算HashMap中的Value的SUM

程序员文章站 2022-05-21 15:17:25
...

统计Redis中HashMap缓存中Value的数据值:

 

local  sizeList = redis.call("HVALS", KEYS[1])
local  total_size = 0
for    index, line in pairs(sizeList) 
do 
       total_size = total_size + tonumber(line)
end
return total_size

 

1. 上传脚本

[eagle@greatwqs src]$ ./redis-cli script load "$(cat /home1/eagle/apps/redis/lua/folder_size.lua)"

"104fc275456ac249b6e266a345d424cf9efe62f4"

2. 造数据

[eagle@greatwqs src]$ ./redis-cli

127.0.0.1:6379> HMSET wqstest folder-1 100 folder-2 200 folder-3 300

OK

127.0.0.1:6379> hvals wqstest

1) "100"

2) "200"

3) "300"

127.0.0.1:6379> exit

3. 使用脚本测试数据

[eagle@greatwqs src]$ ./redis-cli --eval /home1/eagle/apps/redis/lua/folder_size.lua wqstest

(integer) 600

 

PS: 使用脚本造数据

local  redisKey = KEYS[1]
redis.call('DEL', redisKey) 
local total_count = tonumber(KEYS[2])

for loopIndex=1, total_count do
  redis.call('HMSET', redisKey, loopIndex, loopIndex) 
end
return redis.call('HLEN', redisKey) 

[eagle@greatwqs src]$ ./redis-cli --eval /home1/eagle/apps/redis/lua/create_hm_value.lua test 500000

(integer) 500000

造50W条数据, 耗时感觉在秒级别.

 

再用上面第一个脚本计算一下SUM:

[eagle@greatwqs src]$ ./redis-cli --eval /home1/eagle/apps/redis/lua/folder_size.lua test

(integer) 125000250000

很快, 低于500MS就返回了.