3
3
local mysql = require (" resty.mysql" )
4
4
local cjson = require (" cjson" )
5
5
local comm = require (" libs.common" )
6
+ local lrucache = require (" resty.lrucache" )
6
7
7
8
local _M = {}
8
9
10
+ -- we need to initialize the cache on the lua module level so that
11
+ -- it can be shared by all the requests served by each nginx worker process
12
+ local lru_cache = lrucache .new (10 )
9
13
10
- local function cache_mysql (cache_ad )
14
+
15
+ local function cache_mysql ()
11
16
ngx .log (ngx .INFO , " 缓存mysql数据到共享内存" )
12
17
13
18
-- 当前时间
@@ -77,7 +82,7 @@ local function cache_mysql(cache_ad)
77
82
local orig_ad_stage = {}
78
83
79
84
for _ , v in ipairs (res_stage ) do
80
- ngx .say ( v .originalityId )
85
+ ngx .log ( ngx . ERR , ' 缓存广告创意: ' .. v .originalityId )
81
86
local res_orig , err , errno , sqlstate =
82
87
db :query (" select * from orig where originalityId = '" .. v .originalityId .. " '" )
83
88
@@ -110,7 +115,7 @@ local function cache_mysql(cache_ad)
110
115
end
111
116
112
117
if not comm .table_is_empty (orig_ad_stage ) then
113
- cache_ad :set (" ad" , cjson . encode ( orig_ad_stage ) , 1800 )
118
+ lru_cache :set (" ad" , orig_ad_stage , 1800 )
114
119
end
115
120
116
121
local ok , err = db :set_keepalive (60000 , 100 )
123
128
124
129
125
130
function _M .cache ()
126
- local cache_ad = ngx .shared .cache_ad
127
- local ad = cache_ad :get (" ad" )
131
+ local ad = lru_cache :get (" ad" )
128
132
129
133
-- 未过期
130
134
if ad then
@@ -135,9 +139,21 @@ function _M.cache()
135
139
local lock = require " resty.lock"
136
140
local lock = lock :new (" locks_ad" )
137
141
lock :lock (" lock_ad" )
138
- cache_mysql (cache_ad )
142
+ ad = lru_cache :get (" ad" )
143
+ if ad then
144
+ lock :unlock ()
145
+ return
146
+ end
147
+ cache_mysql ()
139
148
lock :unlock ()
140
149
end
141
150
142
151
152
+ function _M .get_ad ()
153
+ local ad = lru_cache :get (" ad" )
154
+
155
+ return ad
156
+ end
157
+
158
+
143
159
return _M
0 commit comments