openresty 连接 redis

本文介绍了如何使用 OpenResty 库中的 resty.redis 模块来连接 Redis 数据库,并进行基本的读写操作,以及使用 pipeline 提高效率和性能。
首先,我们需要引入 resty.redis 模块,并创建一个 Redis 连接:

local redis = require "resty.redis"
local red = redis:new()
red:set_timeouts(1000, 1000, 1000) -- 设置连接超时时间为 1 秒
local ok, err = red:connect("127.0.0.1", 6379) -- 连接 Redis 数据库

连接成功后,我们可以进行基本的读写操作:

ok, err = red:set("dog", "an animal") -- 将 "dog" 键的值设置为 "an animal"
res, err = red:get("dog") -- 获取 "dog" 键的值

接下来,我们可以使用 pipeline 提高效率和性能。pipeline 是一种批量发送 Redis 命令的机制,可以减少网络通信的开销。使用 pipeline 的方式如下:

red:init_pipeline() -- 初始化 pipeline
red:set("cat", "Marry") -- 向 "cat" 键中写入 "Marry"
red:set("horse", "Bob") -- 向 "horse" 键中写入 "Bob"
red:get("cat") -- 获取 "cat" 键中的值
red:get("horse") -- 获取 "horse" 键中的值
local results, err = red:commit_pipeline() -- 提交 pipeline

最后,我们需要释放连接或将连接放回连接池中:

red:set_keepalive(10000, 100) -- 将连接放回连接池中,10 秒内如果有其他请求可以复用这个连接

完整示例

添加redis示例代码

vi /usr/local/openresty/nginx/lua/redis.lua
local redis = require "resty.redis"
local red = redis:new()

red:set_timeouts(1000, 1000, 1000) -- 1 sec

-- or connect to a unix domain socket file listened
-- by a redis server:
--     local ok, err = red:connect("unix:/path/to/redis.sock")

-- connect via ip address directly
local ok, err = red:connect("127.0.0.1", 6379)

if not ok then
    ngx.say("failed to connect: ", err)
    return
end

ok, err = red:set("dog", "an animal")
if not ok then
    ngx.say("failed to set dog: ", err)
    return
end

ngx.say("set result: ", ok)

local res, err = red:get("dog")
if not res then
    ngx.say("failed to get dog: ", err)
    return
end

if res == ngx.null then
    ngx.say("dog not found.")
    return
end

ngx.say("dog: ", res)

red:init_pipeline()
red:set("cat", "Marry")
red:set("horse", "Bob")
red:get("cat")
red:get("horse")
local results, err = red:commit_pipeline()
if not results then
    ngx.say("failed to commit the pipelined requests: ", err)
    return
end

for i, res in ipairs(results) do
    if type(res) == "table" then
        if res[1] == false then
            ngx.say("failed to run command ", i, ": ", res[2])
        else
            -- process the table value
        end
    else
        -- process the scalar value
    end
end

-- put it into the connection pool of size 100,
-- with 10 seconds max idle time
local ok, err = red:set_keepalive(10000, 100)
if not ok then
    ngx.say("failed to set keepalive: ", err)
    return
end

-- or just close the connection right away:
-- local ok, err = red:close()
-- if not ok then
--     ngx.say("failed to close: ", err)
--     return
-- end

nginx.conf文件引用redis.lua

vi /usr/local/openresty/nginx/conf/nginx.conf
# 添加 location /lua
 location /lua {
    
    
    default_type text/html;
    content_by_lua_file lua/redis.lua;
}

在这里插入图片描述

重启nginx

/usr/local/openresty/nginx/sbin/nginx -t
/usr/local/openresty/nginx/sbin/nginx -s reload

访问 localhost:80/lua

在这里插入图片描述
在这里插入图片描述

参考

lua-resty-redis

猜你喜欢

转载自blog.csdn.net/huangjuan0229/article/details/130966837