Skip to content

Commit

Permalink
redis
Browse files Browse the repository at this point in the history
  • Loading branch information
spout committed Mar 20, 2014
1 parent 7a442d7 commit 46d6657
Show file tree
Hide file tree
Showing 4 changed files with 214 additions and 12 deletions.
7 changes: 7 additions & 0 deletions lua/trymenu/lib/conn.lua
Expand Up @@ -6,4 +6,11 @@ connTable = {
database='try_game4',
user='root',
password='123456',
}

connRedis = {
host='192.168.20.62',
port=6379,
pool=30,
max_idle_timeout=1000*10,
}
39 changes: 30 additions & 9 deletions lua/trymenu/lib/mysql_class2.lua
Expand Up @@ -4,6 +4,7 @@ module("mysql_class2", package.seeall)
local mysql = require "resty.mysql"
local dbConn = require "conn"["connTable"]
local dateLib = require "date"
local RedisClass = require "redis_class"["Redis_Class"]

local ERR_MYSQL_LIB = "could not open mysql library"
local ERR_MYSQL_DB = "could not open mysql database"
Expand All @@ -28,7 +29,8 @@ function Mysql_CLass:initialize(reqTable)
self.pool_size = 50
self.reqTable = reqTable --获得filter类的实例
self.jsonTable={}


self.ismain = false
end


Expand Down Expand Up @@ -92,8 +94,20 @@ function Mysql_CLass:query_item()

self.userVersion = self.reqTable.updatetime or nil -- 接受更新时间时间戳

local redis = RedisClass:new(self.reqTable.city, self.userVersion)

local err,str = redis:get_data()

if not err and str then
return nil,str
end

local err,str = self:getDateByDb() --数据库查询


if not err and str and not self.ismain then --如果正常生成str,则保存到缓存
redis:set_data(str,self.version)
end

return err,str
end

Expand All @@ -116,7 +130,7 @@ function Mysql_CLass:getDateByDb() --缓存没有命中,从数据库读取数
if not res then
--如果表查询出错
self:close_conn() -- 关闭数据库连接
ngx.log(ngx.ERR, "get mysql data error: " .. err .. ": " .. errno .. ": ".. sqlstate .. ".") --出错记录错误日志
ngx.log(ngx.ERR, "not get data") --出错记录错误日志
return ERR_MYSQL_ERROR, nil
end

Expand All @@ -125,12 +139,13 @@ function Mysql_CLass:getDateByDb() --缓存没有命中,从数据库读取数
if table.getn(res) == 0 then --如果没有查到数据,使用默认的

sqlCmd = self:genSqlCmd('main') -- 生成sql语句,使用main站点获取
self.ismain = true --表示从主站读取
res, err, errno, sqlstate = db:query(sqlCmd) --查询 ApiServices 表

if not res or table.getn(res)==0 then
--如果表查询出错
self:close_conn() -- 关闭数据库连接
ngx.log(ngx.ERR, "get mysql data main site error: " .. err .. ": " .. errno .. ": ".. sqlstate .. ".") --出错记录错误日志
ngx.log(ngx.ERR, "no res or get err err is:" .. (err or "")) --出错记录错误日志
return ERR_MYSQL_ERROR, nil
end

Expand Down Expand Up @@ -186,9 +201,9 @@ function Mysql_CLass:getDateByDb() --缓存没有命中,从数据库读取数

self.version = ngx.md5(versionStr) --生成版本号

if self.version == self.userVersion then
return nil,'cache'
end
--if self.version == self.userVersion then
-- return nil,'cache'
-- end

self.menuTable = self:filterEmpty() -- 去除空房间的节点

Expand Down Expand Up @@ -216,14 +231,20 @@ function Mysql_CLass:genSqlCmd(site) --创建数据库查询字符串

local now = os.date("%Y-%m-%d %H:%M:%S", os.time())

local property = "GAME_LIST_ITEM.Id, ItemType, Itemname, ItemNewTip, ItemExtraTip, Changed, parentId, Icon, ItemID, ItemUrl, OpenType, Width, Height, ItemParent, mycategorycode, HelpURL, ServerVersion, EName, channelcode, rootcode, mygamecode, WatchCrash, ServerID, GameServerAddr, GameServerPort, MinVer, MaxVer, MaxUser, GameTypeName,"
local property = "GAME_LIST_ITEM.Id, ItemType, Itemname, ItemNewTip, ItemExtraTip, Changed, parentId, Icon, ItemID, ItemUrl, OpenType, Width, Height, ItemParent, mycategorycode, HelpURL, ServerVersion, EName, channelcode, rootcode, mygamecode, WatchCrash, ServerID, GameServerAddr, GameServerPort, MinVer, MaxVer, MaxUser, GameTypeName, Game.ProgName,"

local writeTimeCol = '(CASE\n'..
'WHEN GAME_LIST_ITEM.writetime > IFNULL(Game.writetime, \'2000-01-01\') THEN GAME_LIST_ITEM.writetime \n'..
'ELSE IFNULL(Game.writetime, \'2000-01-01\') \n'..
'END ) AS writetime'

local sqlCmd = "select "..property..writeTimeCol.." from GAME_LIST_ITEM INNER join GAME_SITE on (GAME_LIST_ITEM.GAME_SITEId = GAME_SITE.Id) left join Game on (GAME_LIST_ITEM.GameId = Game.Id) WHERE GAME_LIST_ITEM.is_show=1 AND GAME_SITE.sitename="..ngx.quote_sql_str(site).." AND GAME_LIST_ITEM.BeginTime < '"..now.."' AND GAME_LIST_ITEM.EndTime > '"..now.."' AND (Game.IsRun = 1 or Game.IsRun IS NULL) ORDER BY GAME_LIST_ITEM.Iorder ASC;"
local sqlCmd = "select "..property..writeTimeCol.." from GAME_LIST_ITEM left join Game on (GAME_LIST_ITEM.GameId = Game.Id) WHERE "..
" GAME_SITEId =( SELECT Id FROM GAME_SITE WHERE sitename="..ngx.quote_sql_str(site)..")"..
" AND GAME_LIST_ITEM.is_show=1"..
" AND GAME_LIST_ITEM.BeginTime < '"..now.."'"..
" AND GAME_LIST_ITEM.EndTime > '"..now.."'"..
" AND (Game.IsRun = 1 or Game.IsRun IS NULL)"..
" ORDER BY GAME_LIST_ITEM.Iorder ASC;"

return sqlCmd

Expand Down
173 changes: 173 additions & 0 deletions lua/trymenu/lib/redis_class.lua
@@ -0,0 +1,173 @@
module("redis_class", package.seeall)

local redis = require "resty.redis"
local RedisConn = require "conn"["connRedis"]
local dateLib = require "date"


Redis_Class = class('Redis_Class')

function Redis_Class:initialize(city,userversion)
self.host = RedisConn.host
self.port = RedisConn.port

self.pool=RedisConn.pool
self.max_idle_timeout=RedisConn.max_idle_timeout

self.version = userversion
self.city = city or 'main'

self.cacheTime = 60

end


function Redis_Class:connect()

local red = redis:new()

red:set_timeout(3000) -- 1 second

local ok, err = red:connect(self.host, self.port)

if not ok then
ngx.log(ngx.ERR, "redis library error " .. err) --出错记录错误日志,无法加载mysql库
return ERR_MYSQL_LIB --返回错误code
end

self.red = red

return nil, red --连接成功返回ok状态码

end



function Redis_Class:close_conn() --关闭redis连接封装

local red = self.red

local ok, err = red:set_keepalive(self.max_idle_timeout, self.pool) --将本链接放入连接池

if not ok then --如果设置连接池出错
ngx.log(ngx.ERR, "redis failed to back connect pool: " .. err)
end

end



function Redis_Class:get_data() -- 获取redis缓存数据

local err, red = self:connect()

if err then
return err
end

local now = tonumber(os.time()) --获得当前时间

local res, err = red:get("lastCacheTime") --获取上次缓存时间
if err then --如果失败
self:close_conn()
ngx.log(ngx.ERR, "failed to get lastCacheTime: ", err)
return err
end

if res == ngx.null then --如果没获取到 上一次缓存时间
self:close_conn()
ngx.log(ngx.WARN, "no lastCacheTime")
return 'no lastCacheTime'
end

local lastCacheTime = tonumber(res)

if now - lastCacheTime > self.cacheTime then --如果缓存已经失效
self:close_conn()
ngx.log(ngx.INFO, "cache expired lastCacheTime is " .. tostring(lastCacheTime))
return 'cache expired'
end

--如果满足上述条件,则去redis拿缓存


if not self.version then
return self:send_cache_jsonstr()
end

local key = self.city .. '_version'
local version, err = red:get(key) --获取此city城市的版本号
if err then --如果失败
self:close_conn()
ngx.log(ngx.ERR, 'failed to get '..key..'err: ',err)
return err
end

if version == ngx.null then --如果没获取到次版本号的city,则返回此city下面的缓存jsonstr
ngx.log(ngx.WARN, "no city version")
return self:send_cache_jsonstr()
end


if version ~= self.version then --如果用户当前版本号与数据库不同,则响应redis字符串
return self:send_cache_jsonstr()
else --如果版本号相符,就返回cache字符串
--ngx.log(ngx.INFO, 'hit cache return cache')
self:close_conn()
return nil,'cache'
end

end


function Redis_Class:send_cache_jsonstr()

local keyJson = self.city .. '_json'
local res, err = self.red:get(keyJson) --获取此city城市的版本号
self:close_conn()
if err then --如果失败
ngx.log(ngx.ERR, 'failed to get '..keyJson..'err: ',err)
return err
end
if res == ngx.null then --如果没获取到缓存内容
ngx.log(ngx.WARN, 'no cache data,key is',keyJson)
return 'no cache data'
end

--ngx.log(ngx.INFO, 'hit cache return jsonstr')
return nil,res --找到缓存json字符串,返回

end




function Redis_Class:set_data(jsonstr,version)

local err, red = self:connect()

if err then
return err
end

local keyJson = self.city .. '_json' -- 城市json字符串key
local keyVersion = self.city .. '_version' -- 城市版本号key

red:init_pipeline() --管道生成
red:set('lastCacheTime', os.time()) -- 存入城市json缓存
red:set(keyJson, jsonstr) -- 存入城市json缓存
red:set(keyVersion, version) -- 存入城市版本号值

local res, err = red:commit_pipeline() --执行
self:close_conn()

if err then -- 如果生成缓存失败,记录日志
ngx.log(ngx.WARN, 'create '..self.city..' err :',err)
return err
end
ngx.log(ngx.INFO, 'create '..self.city..' cache success')
return nil

end


7 changes: 4 additions & 3 deletions lua/trymenu/menu.lua
Expand Up @@ -13,8 +13,11 @@ if err then
return ngx.say(err)
end

--ngx.say(json)
if args.noencode then

return ngx.say(json)

end

local XorKey = 4
local s = ngx.encode_base64(json)
Expand All @@ -25,8 +28,6 @@ for i=1,#s do
end
local s2 = table.concat(stable)



-- ngx.header["Content-Type"] = 'application/json; charset=UTF-8';

ngx.say(s2)
Expand Down

0 comments on commit 46d6657

Please sign in to comment.