ngx_lua访问数据库
2016-04-07 16:10
357 查看
https://github.com/openresty/lua-resty-mysql 张宜春大师写的mysql链接模块
利用大神的模块,下面是我写的一个验证的函数,通过用户session判断这次访问是否合法。
利用大神的模块,下面是我写的一个验证的函数,通过用户session判断这次访问是否合法。
function F.check_session() local uid = args["uid"] local session = args["session"] local mysql = require "mysql" if uid == nil or uid == 0 then ngx.exit(403) end local db, err = mysql:new() if not db then ngx.say("failed to instantiate mysql: ", err) return end db:set_timeout(1000) -- 1 sec local ok, err, errno, sqlstate = db:connect{ host = "127.0.0.1", port = 3306, database = "xxx", user = "root", password = "xxx", max_packet_size = 1024 * 1024 } if not ok then ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate) return end sql = "SELECT * FROM `sessions` WHERE `uid` = ".. uid .. " and `session_id` = " .."\"" .. session .."\"" res, err, errno, sqlstate = db:query(sql) if not res then ngx.header["ID_Error"] = "sql error" ngx.exit(403) elseif #(res) > 0 then --local cjson = require "cjson" local time_now = os.time() local last_time = tonumber(res[1]["last_activity"]) + tonumber(res[1]["life_time"]) if last_time <= time_now then ngx.exit(403) end --[[ local session = args["session"] local session_id = res[1]["session_id"] if session ~= session_id then ngx.header["ID_Error"] = "error session" ngx.exit(403) end --]] else ngx.header["ID_Error"] = "sqldate error" ngx.exit(403) end end
相关文章推荐
- MySQL中的integer 数据类型
- MySQL存储过程
- mysql中int、bigint、smallint 和 tinyint的区别与长度
- mysql load data 导出、导入 csv
- source命令执行SQL脚本文件
- MySQL创建用户及权限控制
- MySQL管理数据表
- linux下mysql添加用户
- mysql procedure
- mysql触发器
- MySQL 备份和恢复策略
- mac下安装mysql(转载)
- mysql 修改编码 Linux/Mac/Unix/通用(杜绝修改后无法启动的情况!)
- MySQL数据的导出、导入(mysql内部命令:mysqldump、mysql)
- mysql数据行转列
- Linux下修改MySQL编码的方法
- MySQL Server 日志
- MySQL 安全事宜
- MySQL 备份与恢复