1. 程式人生 > >nginx 學習筆記(五)nginx_lua 如何連線redis

nginx 學習筆記(五)nginx_lua 如何連線redis

安裝redis

下載

wget http://download.redis.io/releases/ redis-5.0-rc4.tar.gz

 解壓安裝配置

make, sudo make install

執行redis

配置檔案:redis.conf可以編輯相關內容,預設埠是6379

啟動redis

切換到 redis解壓的目錄的src下面執行 ./redis-server & 使其後臺執行

 

1、對應的nginx.conf配置如下,需要在http模組中新增如下配置,不然在redis.lua中引入的包會報找不到對應的引用錯誤。

http {
   lua_package_path 
  "/usr/local/openresty/nginx/conf/waf/?.lua;/usr/local/openresty/lualib/resty/?.lua;;";
   lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
   lua_shared_dict limit 10m;
   init_by_lua_file /usr/local/openresty/nginx/conf/waf/init.lua;
   access_by_lua_file /usr/local/openresty/nginx/conf/waf/waf.lua;


......其他省略.........
}

 

2、nginx_lua 如何連線redis,對應的lua指令碼(redis.lua)如下。

local cjson = require "cjson"
local redis = require "resty.redis" 
-- 是否需要開啟redis的日誌
attackredislog = "on"
--log儲存目錄,該目錄需要使用者自己新建,切需要使用者的可寫許可權
logdir = "/usr/local/openresty/nginx/logs/hack/"

function redislog(method,data)
    if attackredislog then
	    local servername=ngx.var.server_name
		line = ""..method.." \""..data.."\" \n"
        local filename = logdir..'/'..servername.."_"..ngx.today().."_redis.log"
        write(filename,line)
    end
end

function write(logfile,msg)
    local fd = io.open(logfile,"ab")
    if fd == nil then return end
    fd:write(msg)
    fd:flush()
    fd:close()
end

--------------------------------------------------------


local function close_redis(red)
    if not red then
        return
    end
    --釋放連線(連線池實現)
    local pool_max_idle_time = 10000 --毫秒
    local pool_size = 100 --連線池大小
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
 
    if not ok then
	   redislog("redis keepalive","set redis keepalive error,"..err.."")
    end
end
 

local red = redis:new()
red:set_timeout(1000)
local ip = "127.0.0.1"
local port = 6379
local ok, err = red:connect(ip,port)
if not ok then
    return close_redis(red)
end


function setRedis(key, val)
  local ok, err = red:set(key, val)
   -- 設定值的有效期為60秒
   ok, err = red:expire(key,60)
   if not ok then
    redislog("redis set","failed to set "..key..","..err.."")
    return
    end
end
 
function getRedis(key)
    local res, err = red:get(key)
    if not res then
	redislog("redis get","failed to get,"..err.." ")
    return 
   end
 
  if res == ngx.null then
    redislog("redis get"," "..key.." not found")
    return nil
  else
    return res
  end
end


local ck = ngx.var.http_cookie
local scheme = ngx.var.scheme  
local server_name = ngx.var.server_name
local request_uri = ngx.var.request_uri
local server_port = ngx.var.server_port
local url = scheme.."://"..server_name..":"..server_port..request_uri
local value
if (ck ~= nil) then
 value = getRedis(ck)
end


close_redis(red)