Divide the MSB source codes into two repos
[msb/apigateway.git] / openresty-ext / src / assembly / resources / openresty / nginx / luaext / lib / tools / db_cache.lua
1 --[[\r
2 \r
3     Copyright (C) 2016 ZTE, Inc. and others. All rights reserved. (ZTE)\r
4 \r
5     Licensed under the Apache License, Version 2.0 (the "License");\r
6     you may not use this file except in compliance with the License.\r
7     You may obtain a copy of the License at\r
8 \r
9             http://www.apache.org/licenses/LICENSE-2.0\r
10 \r
11     Unless required by applicable law or agreed to in writing, software\r
12     distributed under the License is distributed on an "AS IS" BASIS,\r
13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
14     See the License for the specific language governing permissions and\r
15     limitations under the License.\r
16 \r
17 --]]\r
18 \r
19 -- db cache over LRUCache, used within one worker processes\r
20 local _M = {}\r
21 _M._VERSION = '1.0.0'\r
22 \r
23 local lrucache = require "resty.lrucache"\r
24 \r
25 local EMPTY_DATA = '_EMPTY_'\r
26 \r
27 -- we need to initialize the cache on the lua module level so that\r
28 -- it can be shared by all the requests served by each nginx worker process:\r
29 local cache,err = lrucache.new(200)  -- allow up to 200 items in the cache\r
30 if not cache then\r
31         return ngx.log(ngx.ERR,"failed to create the cache: " .. (err or "unknown"))\r
32 end\r
33 \r
34 function _M.get(key)\r
35         return cache:get(key)\r
36 end\r
37 \r
38 function _M.set(key,value)\r
39         return _M:set(key, value, nil)\r
40 end\r
41 \r
42 function _M.set(key,value,ttl)\r
43         if not value then \r
44                 value = EMPTY_DATA\r
45         end\r
46         return cache:set(key, value, ttl)\r
47 end\r
48 \r
49 -- check if the data returned by get() is considered empty\r
50 function _M.is_empty(data)\r
51         return data == EMPTY_DATA\r
52 end\r
53 \r
54 return _M