Openresty | redis客户端

openresty开发库

redis客户端

配置openresty连接redis

# 基本操作
local redis = require("resty.redis")

-- close redis
local function close_redis(instance)
    if not instance then
        return
    end

    local ok, error = instance:close()
    if not ok then
        ngx.say(error)
    end
end

-- open redis
local redis_ip = "127.0.0.1"
local redis_port = "6379"

local redis_instance = redis:new()
redis_instance:set_timeout(1000)
local ok, error = redis_instance.connect(redis_ip, redis_port)
if not ok then
    ngx.say(error)
    return close_redis(redis_instance)
end

-- set/get key
local redis_key = "message"
local redis_value = ngx.md5("hello, world")

ok, error = redis_instance:set(redis_key, redis_value)
if not ok then
    ngx.say(error)
    return close_redis(redis_instance)
end

local message, error = redis_instance:get(redis_key)
if not message then
    ngx.say(error)
    return close_redis(redis_instance)
end

if message == ngx.null then
    message = ""
end
ngx.say(redis_key, ": ", message)
close_redis(redis_instance)

连接池

local function close_redis(instance)
    if not instance then
        return
    end

    local pool_max_idle_time = 10000    -- 毫秒
    local pool_size = 100               -- 连接池大小
    local ok, error = instance:set_keepalive(pool_max_idle_time, pool_size)
    if not ok then
        ngx.say(error)
    end
end

# pipeline
red:init_pipeline()
red:set("key-01", "value-01")
red:set("key-02", "value-02")
red:get("key-01")
red:get("key-02")
local response, err = red:commit_pipeline()

if response == ngx.null then
    response = {}
end

for i, v in ipairs(response) do
    ngx.say(i, ": ", v)
end

-- 执行结果
1: OK
2: OK
3: value-01
4: value-02

你可能感兴趣的:(Openresty | redis客户端)