lua 操作redis 加减脚本
时间: 2023-08-07 13:06:44 浏览: 49
以下是 Lua 操作 Redis 加减脚本的示例代码:
```lua
-- 连接 Redis
local redis = require "resty.redis"
local red = redis:new()
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
ngx.say("failed to connect: ", err)
return
end
-- 定义加减脚本
local script = [[
local key = KEYS[1]
local num = tonumber(ARGV[1])
local curr = tonumber(redis.call('get', key) or 0)
local new = curr + num
redis.call('set', key, new)
return new
]]
-- 执行加减脚本
local res, err = red:eval(script, 1, "mykey", "10")
if not res then
ngx.say("failed to execute script: ", err)
return
end
-- 输出结果
ngx.say(res)
-- 关闭 Redis 连接
red:close()
```
该脚本实现了对 Redis 中指定 key 的值进行加法操作,并返回操作后的结果。其中,`KEYS[1]` 表示第一个参数为 Redis key,`ARGV[1]` 表示第二个参数为要加的数字。执行加减脚本的方式是使用 `eval` 命令,第一个参数为脚本内容,后面的参数为脚本中用到的参数。