openresty ngx_lua共享内存


openresty ngx_lua共享内存

         

lua_shared_dict:https://github.com/openresty/lua-nginx-module#lua_shared_dict

ngx.shared.DICT:https://github.com/openresty/lua-nginx-module#ngxshareddict

           

                     

                                  

创建共享内存

            

lua_shared_dict:创建共享内存

语法格式:lua_shared_dict  
* name:共享内存名称
* size:共享内存大小,单位m、k,最小12k,低于12k会报错
* 创建的内存所有worker共享,一个worker进程修改数据后,对其他worker可见,读写共享内存需要加锁
* 共享内存预先分配,如果内存不足,会使用lru(最近最少使用算法)清理缓存
* 可以创建多个共享内存

上下文环境:http

         

示例


 http {
     lua_shared_dict dogs 10m;
     ...
 }

        

            

                                  

获取共享空间

            

ngx.shared.DICT:获取共享空间

# 语法格式
dict = ngx.shared.DICT
dict = ngx.shared[name_var]
* 获取共享空间
* DICT、name_var:表示lua_shared_dict中定义的共享空间名称

环境:init_by_lua*, init_worker_by_lua*, log_by_lua*, ngx.timer.*, 
     set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, balancer_by_lua*,  
     ssl_certificate_by_lua*, exit_worker_by_lua*, 
     ssl_session_fetch_by_lua*, ssl_session_store_by_lua*, 
     ssl_client_hello_by_lua*

            

示例


 http {
     lua_shared_dict dogs 10m;    # 设置共享内存空间
     server {
         location /set {
             content_by_lua_block {
                 local dogs = ngx.shared.dogs   --获取共享内存空间
                 dogs:set("Jim", 8)             --设置key、value
                 ngx.say("STORED")
             }
         }
         location /get {
             content_by_lua_block {
                 local dogs = ngx.shared.dogs
                 ngx.say(dogs:get("Jim"))       --获取key对应的value
             }
         }
     }
 }

        

                  

                                  

获取缓存值

            

ngx.shared.DICT.get:获取缓存值

语法格式:value, flags = ngx.shared.DICT:get(key)
* 获取共享内存key对应的value
* 如果key不存在、活着过期,返回nil
* 如果出错,返回nil、错误信息err
* flags:是否做了标识,一般在set操作时设置,如果没有设置,默认为0

环境:set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*,
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*

         

ngx.shared.DICT.get_stale:获取缓存值,可以返回过期值

语法格式:value, flags, stale = ngx.shared.DICT:get_stale(key)
* 与get操作类似,get_stale可以返回过期值

环境:set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*

            

示例

# 以下两种方式等价
 local cats = ngx.shared.cats
 local value, flags = cats.get(cats, "Marry")

==>

 local cats = ngx.shared.cats
 local value, flags = cats:get("Marry")

           

                 

                                  

设置缓存

            

ngx.shared.DICT.set:设置缓存

语法格式:success, err, forcible = ngx.shared.DICT:set(key, value, exptime?, flags?)
* 设置缓存值,会覆盖相同的key
* 内存空间不足时,使用lru算法删除缓存,优先于根据过期时间删除
* exptime:过期时间,精确到0.001s,0表示不过期,可选
* flags:标识,默认0,可选

* success:是否设置成功
* err:错误信息,no memory表示缓存空间不足
* forcible:设置key、value时,其他相同的key是否被删除,true删除、false没有删除

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*

             

ngx.shared_DICT.safe_set:设置缓存,不会覆盖已经存在但未过期的缓存

语法格式:ok, err = ngx.shared.DICT:safe_set(key, value, exptime?, flags?)
* 与set操作类似,内存空间不足时,不会覆盖已经存在,但是没有过期的缓存

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*

         

示例

# 以下两种方式等价
 local cats = ngx.shared.cats
 local succ, err, forcible = cats.set(cats, "Marry", "it is a nice cat!")

==>

 local cats = ngx.shared.cats
 local succ, err, forcible = cats:set("Marry", "it is a nice cat!")

         

            

                                  

添加缓存

            

ngx.shared.DICT.add:key不存在时添加缓存

语法格式:success, err, forcible = ngx.shared.DICT:add(key, value, exptime?, flags?)
* key不存在时添加缓存

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Just like the set method, but only stores the key-value pair 
into the dictionary ngx.shared.DICT if the key does not exist.
* 和set方法作用类似,但是只有当key不存在时,才会添加缓存

If the key argument already exists in the dictionary (and not 
expired for sure), the success return value will be false and 
the err return value will be "exists"
* 如果key存在,success返回false、err返回exists

             

ngx.shared.DICT.safe_add:key不存在时添加缓存,内存不足时不会添加

语法格式:ok, err = ngx.shared.DICT:safe_add(key, value, exptime?, flags?)
* key不存在时添加缓存
* 内存空间不足时,不会添加缓存

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*

Similar to the add method, but never overrides the (least recently 
used) unexpired items in the store when running out of storage in 
the shared memory zone. In this case, it will immediately return 
nil and the string "no memory".
* 和add方法类似,但是内存空间不足时,不会覆盖没有过期的缓存
* 内存不足时,返回nil、no memory

             

示例

# 以下两种方式等价
 local cats = ngx.shared.cats
 local succ, err, forcible = cats.add(cats, "Marry", "it is a nice cat!")

==>

 local cats = ngx.shared.cats
 local succ, err, forcible = cats:add("Marry", "it is a nice cat!")

        

               

                                  

替换缓存

            

ngx.shared.DICT.replace:替换缓存

语法格式:success, err, forcible = ngx.shared.DICT:replace(key, value, exptime?, flags?)
* key存在时,替换缓存

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*

Just like the set method, but only stores the key-value pair 
into the dictionary ngx.shared.DICT if the key exists.
* 和set方法类似,但是只有当key存在时,才会替换缓存

If the key argument does not exist in the dictionary (or 
expired already), the success return value will be false 
and the err return value will be "not found"
* 如果key不存在,success返回false、err返回not found

              

                   

                                  

删除缓存

            

ngx.shared.DICT.delete:删除缓存

语法格式:ngx.shared.DICT:delete(key)
* 删除缓存

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Unconditionally removes the key-value pair from the shm-based dictionary 
ngx.shared.DICT. It is equivalent to ngx.shared.DICT:set(key, nil)
*删除缓存,和ngx.shared.DICT:set(key, nil)方法等效

          

               

                                  

缓存自增

            

ngx.shared.DICT.incr:缓存数值自增

语法格式:newval, err, forcible? = ngx.shared.DICT:incr(key, value, init?, init_ttl?)
* 缓存数值自增
* init_ttl:设置缓存过期时间,精确到0.001s,设置为0表示没有过期时间
* init:初始值,如果key不存在、或者过期时,返回init + value
* forcible:如果通过清除其他缓存自增成功,返回true,否则返回false
            如果没有设置init,该值始终返回false

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Increments the (numerical) value for key in the shm-based dictionary 
ngx.shared.DICT by the step value value. Returns the new resulting 
number if the operation is successfully completed or nil and an 
error message otherwise.
* 给key对应的值加上value
* 设置成功,返回新的数值
* 设置失败,返回nil、错误信息

When the key does not exist or has already expired in the shared dictionary,
   * if the init argument is not specified or takes the value nil, 
     this method will return nil and the error string "not found", or
   * if the init argument takes a number value, this method will 
     create a new key with the value init + value.
* 如果key不存在、活着过期了
 * init没有设置,返回nil、not found
 * init设置了,创建新的key,返回init + value

Like the set method, it also overrides the (least recently used) 
unexpired items in the store when running out of storage in the 
shared memory zone.
* 和set操作类似,也会在内存不足时,替换没有过期的缓存

          

示例

 require "resty.core"

 local cats = ngx.shared.cats
 local newval, err = cats:incr("black_cats", 1, 0, 0.1)

 print(newval) -- 1

 ngx.sleep(0.2)

 local val, err = cats:get("black_cats")
 print(val) -- nil

         

               

                                  

过期时间

            

ngx.shared.DICT.ttl:查看key的剩余存活时间

语法格式:ttl, err = ngx.shared.DICT:ttl(key)
* 获取key的剩余存活时间

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Retrieves the remaining TTL (time-to-live in seconds) of a 
key-value pair in the shm-based dictionary ngx.shared.DICT. 
Returns the TTL as a number if the operation is successfully 
completed or nil and an error message otherwise.
* 获取key、value键值对的剩余存活时间,返回数字
* 如果获取失败,返回nil、错误信息

If the key does not exist (or has already expired), this method 
will return nil and the error string "not found".
* 如果key不存在,返回nil、not found

The TTL is originally determined by the exptime argument of the 
set, add, replace (and the likes) methods. It has a time resolution 
of 0.001 seconds. A value of 0 means that the item will never expire
* ttl是由set、add、replace等方法设置的exptime计算得到的
* 0表示key永远不过期

        

ngx.shared.DICT.expire:设置过期时间

语法格式:uccess, err = ngx.shared.DICT:expire(key, exptime)
* 更新key的过期时间
* 需要resty-core、或者resty-core-shdict

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Updates the exptime (in second) of a key-value pair in the shm-based 
dictionary ngx.shared.DICT. Returns a boolean indicating success if 
the operation completes or nil and an error message otherwise.
* 更新key的剩余过期时间,设置成功返回true
* 如果设置失败,返回nil、错误信息

If the key does not exist, this method will return nil and the error 
string "not found".
* 如果key不存在,返回nil、not found

The exptime argument has a resolution of 0.001 seconds. If exptime is 
0, then the item will never expire
* 过期时间精度为0.001s
* 如果设置为0,表示永不过期

            

示例:查看剩余存活时间


 require "resty.core"

 local cats = ngx.shared.cats
 local succ, err = cats:set("Marry", "a nice cat", 0.5)

 ngx.sleep(0.2)

 local ttl, err = cats:ttl("Marry")
 ngx.say(ttl) -- 0.3

           

示例:更新过期时间

 require "resty.core"

 local cats = ngx.shared.cats
 local succ, err = cats:set("Marry", "a nice cat", 0.1)

 succ, err = cats:expire("Marry", 0.5)

 ngx.sleep(0.2)

 local val, err = cats:get("Marry")
 ngx.say(val) -- "a nice cat"

          

                 

                                  

清理操作

            

ngx.shared.DICT.flush_all:使所有的key都过期,不执行清理操作

语法格式:ngx.shared.DICT:flush_all()
* 使所有的key都过期

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Flushes out all the items in the dictionary. This method does not 
actually free up all the memory blocks in the dictionary but just 
marks all the existing items as expired
* 清理所有的key
* 不做清理操作,只是把key都设为过期

             

ngx.shared.DICT.flush_expire:清理过期key

语法格式:flushed = ngx.shared.DICT:flush_expired(max_count?)
* 清理过期的key
* max_count:表示最多清理的key的数量,0表示清理全部

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Flushes out the expired items in the dictionary, up to the 
maximal number specified by the optional max_count argument. 
When the max_count argument is given 0 or not given at all, 
then it means unlimited. Returns the number of items that 
have actually been flushed.
* 清理所有过期的key,最大数量为max_count
* 如果max_count=0,或者没有设置,则会清理全部过期的key
* 返回清理的key的数量

Unlike the flush_all method, this method actually frees up the 
memory used by the expired items
* flush_expire会执行清理操作

          

              

                                  

获取所有的key

            

ngx.shared.DICT.get_keys:获取所有的key

语法格式:keys = ngx.shared.DICT:get_keys(max_count?)
* 获取缓存的key
* max_count:表示最多获取的key的数量,0表示清理全部

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Fetch a list of the keys from the dictionary, up to .
* 获取的key,最多max_countge

By default, only the first 1024 keys (if any) are returned. When 
the  argument is given the value 0, then all the keys 
will be returned even there is more than 1024 keys in the dictionary.
* max_count如果没有设置,默认获取1024个
* max_count如果设置为0,返回所有的key

CAUTION Avoid calling this method on dictionaries with a very large 
number of keys as it may lock the dictionary for significant amount 
of time and block Nginx worker processes trying to access the dictionary
* 注意:应该避免获取所有的key,这可能会造成worker进程的阻塞

             

                    

                                  

缓存空间大小

            

ngx.shared.DICT.capacity:缓存空间大小

语法格式:capacity_bytes = ngx.shared.DICT:capacity()
* 获取缓存空间大小
* 需要resty-core、或者resty-core-shdict

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Retrieves the capacity in bytes for the shm-based dictionary 
ngx.shared.DICT declared with the lua_shared_dict directive.
* 获取缓存空间大小(lua_shared_dict设置的大小),单位字节

             

ngx.shared.DICT.free_capacity:剩余可用空间

语法格式:free_page_bytes = ngx.shared.DICT:free_space()
* 获取剩余可用空间大小
* 需要resty-core、或者resty-core-shdict

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Retrieves the free page size in bytes for the shm-based dictionary 
ngx.shared.DICT.
* 获取剩余可用空间大小,单位字节

Note: The memory for ngx.shared.DICT is allocated via the Nginx 
slab allocator which has each slot for data size ranges like ~8, 
9~16, 17~32, ..., 1025~2048, 2048~ bytes. And pages are assigned 
to a slot if there is no room in already assigned pages for the slot.
* 注意:内存是用nginx slab内存分配器分配的

So even if the return value of the free_space method is zero, there
 may be room in already assigned pages, so you may successfully set 
a new key value pair to the shared dict without getting true for 
forcible or non nil err from the ngx.shared.DICT.set.
* 因此,即使free_space()返回0,还是有可能设置新的key(不需要删除缓存)

On the other hand, if already assigned pages for a slot are full and 
a new key value pair is added to the slot and there is no free page, 
you may get true for forcible or non nil err from the ngx.shared.DICT.set method.
* 如果没有可用内存,还是有可能通过回收内存,设置新的key

          

示例:查看缓存空间

 require "resty.core.shdict"

 local cats = ngx.shared.cats
 local capacity_bytes = cats:capacity()

          

示例:查看剩余可用缓存大小

 require "resty.core.shdict"

 local cats = ngx.shared.cats
 local free_page_bytes = cats:free_space()

          

                

                                  

队列操作

            

ngx.shared.DICT.lpush:从左端插入列表

语法格式:length, err = ngx.shared.DICT:lpush(key, value)

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Inserts the specified (numerical or string) value at the head of the 
list named key in the shm-based dictionary ngx.shared.DICT. Returns 
the number of elements in the list after the push operation.
* 从头部插入元素,返回插入后的列表元素个数

If key does not exist, it is created as an empty list before performing 
the push operation. When the key already takes a value that is not a list, 
it will return nil and "value not a list".
* 如果key不存在,创建一个空的列表,并将元素插入
* 如果key不是列表,返回nil、value not a list

It never overrides the (least recently used) unexpired items in the 
store when running out of storage in the shared memory zone. In this 
case, it will immediately return nil and the string "no memory"
* 内存空间不足,不会覆盖已有的元素,会返回nil、no memory

           

ngx.shared.DICT.rpush:从右端插入元素

语法格式:length, err = ngx.shared.DICT:rpush(key, value)

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Similar to the lpush method, but inserts the specified (numerical 
or string) value at the tail of the list named key
* 和lpush功能类似,从尾部插入元素(数字或者字符串)

             

ngx.shared.DICT.lpop:从头部弹出元素

语法格式:val, err = ngx.shared.DICT:lpop(key)

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Removes and returns the first element of the list named key in 
the shm-based dictionary ngx.shared.DICT.
* 取出并移除第一个元素

If key does not exist, it will return nil. When the key already takes 
a value that is not a list, it will return nil and "value not a list"
* 如果key不存在,返回nil
* 如果key不是list,返回nil、value not a list

                  

ngx.shared.DICT.rpop:从尾部弹出元素

语法格式:val, err = ngx.shared.DICT:lpop(key)

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Removes and returns the last element of the list named key in the 
shm-based dictionary ngx.shared.DICT.
* 取出并移除最后个元素

If key does not exist, it will return nil. When the key already takes 
a value that is not a list, it will return nil and "value not a list"
* 如果key不存在,返回nil
* 如果key不是list,返回nil、value not a list

            

ngx.shared.DICT.llen:返回列表元素的个数

语法格式:len, err = ngx.shared.DICT:llen(key)

环境:init_by_lua*, set_by_lua*, rewrite_by_lua*, access_by_lua*, content_by_lua*, 
     header_filter_by_lua*, body_filter_by_lua*, log_by_lua*, ngx.timer.*, 
     balancer_by_lua*, ssl_certificate_by_lua*, ssl_session_fetch_by_lua*, 
     ssl_session_store_by_lua*, ssl_client_hello_by_lua*


Returns the number of elements in the list named key in the 
shm-based dictionary ngx.shared.DICT.
* 返回列表元素的个数

If key does not exist, it is interpreted as an empty list and 
0 is returned. When the key already takes a value that is not 
a list, it will return nil and "value not a list"
* 如果key不存在,返回0
* 如果key不是list,返回nil、value not a list

          

                

                                  

使用示例

            

nginx.conf

pcre_jit on;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    client_body_temp_path /var/run/openresty/nginx-client-body;
    proxy_temp_path       /var/run/openresty/nginx-proxy;
    fastcgi_temp_path     /var/run/openresty/nginx-fastcgi;
    uwsgi_temp_path       /var/run/openresty/nginx-uwsgi;
    scgi_temp_path        /var/run/openresty/nginx-scgi;

    sendfile        on;

    keepalive_timeout  65;

    include /etc/nginx/conf.d/*.conf;

    #设置共享缓存
    lua_shared_dict test 10m;
}

          

default.conf

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/local/openresty/nginx/html;
        index  index.html index.htm;
    }

    location /test {
        content_by_lua_block {
            local cache = ngx.shared.test;

            ngx.say("设置缓存 ==> ", 'cache:set("1", "瓜田李下")')
            local success, err, forcible = cache:set("1", "瓜田李下");
            if not success then 
                ngx.say("缓存设置失败");
            end

            ngx.say("获取缓存 ==> ", 'cache:get("1")');
            local value, flags = cache:get("1");
            if not value then
                ngx.say("获取缓存失败");
            end
            ngx.say("缓存value ==>", value);
        }
    }

    location /test2 {
        content_by_lua_block {
            local cache = ngx.shared.test;

            ngx.say("设置缓存 ==> ", 'cache:set("3", "瓜田李下")')
            local success, err, forcible = cache:set("3", "瓜田李下");
            if not success then
                ngx.say("缓存设置失败");
            end

            ngx.say("add缓存 ==> ", 'cache:add("3", "海贼王")')
            local success, err, forcible = cache:add("3", "海贼王");
            if not success then
                ngx.say("add 3 ==> 缓存失败");
            end

            ngx.say("add缓存 ==> ", 'cache:add("4", "海贼王")')
            local success, err, forcible = cache:add("4", "海贼王");
            if not success then
                ngx.say("add 4 ==> 缓存失败");
            end

            ngx.say("获取缓存 3 ==> ", 'cache:get("3")');
            local value, flags = cache:get("3");
            if not value then
                ngx.say("获取缓存3 失败");
            end
            ngx.say("缓存 3 value ==>", value);

            ngx.say("获取缓存 4 ==> ", 'cache:get("4")');
            local value, flags = cache:get("4");
            if not value then
                ngx.say("获取缓存4 失败");
            end
            ngx.say("缓存 4 value ==>", value);
        }
    }

    location /test3 {
        content_by_lua_block {
            local cache = ngx.shared.test;

            ngx.say("设置缓存 ==> ", 'cache:set("5", "瓜田李下")')
            local success, err, forcible = cache:set("5", "瓜田李下");
            if not success then
                ngx.say("缓存设置失败");
            end

            ngx.say("replace缓存 ==> ", 'cache:replace("5", "海贼王")')
            local success, err, forcible = cache:replace("5", "海贼王");
            if not success then
                ngx.say("replace 5 ==> 缓存失败");
            end

            ngx.say("replace缓存 ==> ", 'cache:replace("6", "瓜田李下")')
            local success, err, forcible = cache:replace("6", "瓜田李下");
            if not success then
                ngx.say("replace 6 ==> 缓存失败");
            end

            ngx.say("获取缓存 5 ==> ", 'cache:get("5")');
            local value, flags = cache:get("5");
            if not value then
                ngx.say("获取缓存5 失败");
            end
            ngx.say("缓存 5 value ==>", value);

            ngx.say("获取缓存 6 ==> ", 'cache:get("6")');
            local value, flags = cache:get("6");
            if not value then
                ngx.say("获取缓存6 失败");
            end
            ngx.say("缓存 6 value ==>", value);
        }
    }

    location /test4 {
        content_by_lua_block {
             local cache = ngx.shared.test;

             ngx.say("插入列表数据 lpush")
             local len, err = cache:lpush('list','gtlx');
             if not len then
                 ngx.say("插入列表数据失败");
             end
             ngx.say("插入数据后列表长度为 ==> ", len)

             ngx.say("取出列表数据 rpop");
             local val, err = cache:rpop('list');
             if not val then
                 ngx.say("取出列表数据失败");
             end

             ngx.say("列表数据 ==> ", val);
        }
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/openresty/nginx/html;
    }

}

创建容器

docker run -it -d --net fixed --ip 172.18.0.101 -p 8001:80 \
-v /Users/huli/lua/openresty/cache/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf \
-v /Users/huli/lua/openresty/cache/default3.conf:/etc/nginx/conf.d/default.conf \
--name open-cache lihu12344/openresty

           

使用测试

# 设置、获取缓存
huli@hudeMacBook-Pro cache % curl localhost:8001/test 
设置缓存 ==> cache:set("1", "瓜田李下")
获取缓存 ==> cache:get("1")
缓存value ==>瓜田李下

# add缓存:key不存在时添加缓存
huli@hudeMacBook-Pro cache % curl localhost:8001/test2
设置缓存 ==> cache:set("3", "瓜田李下")
add缓存 ==> cache:add("3", "海贼王")
add 3 ==> 缓存失败
add缓存 ==> cache:add("4", "海贼王")
add 4 ==> 缓存失败
获取缓存 3 ==> cache:get("3")
缓存 3 value ==>瓜田李下
获取缓存 4 ==> cache:get("4")
缓存 4 value ==>海贼王

# replace缓存:key存在时替换缓存
huli@hudeMacBook-Pro cache % curl localhost:8001/test3
设置缓存 ==> cache:set("5", "瓜田李下")
replace缓存 ==> cache:replace("5", "海贼王")
replace缓存 ==> cache:replace("6", "瓜田李下")
replace 6 ==> 缓存失败
获取缓存 5 ==> cache:get("5")
缓存 5 value ==>海贼王
获取缓存 6 ==> cache:get("6")
获取缓存6 失败
缓存 6 value ==>nil

# 队列操作
huli@hudeMacBook-Pro cache % curl localhost:8001/test4
插入列表数据 lpush
插入数据后列表长度为 ==> 1
取出列表数据 rpop
列表数据 ==> gtlx

                  

                          

你可能感兴趣的:(openresty,openresty)