nginx 学习笔记(五)nginx_lua 如何连接redis

开发十年,就只剩下这套Java开发体系了 >>>   hot3.png

安装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)

 

你可能感兴趣的:(nginx 学习笔记(五)nginx_lua 如何连接redis)