概念

1
ngx_lua 提供了一系列共享内存相关的 API (ngx.shared.DICT),可以很方便地通过设置过期时间来使得缓存被动过期,值得一提的是,当缓存的容量超过预先申请的内存池大小的时候,ngx.shared.DICT.set 方法则会尝试以 LRU 的形式淘汰一部分内容。

常用方法(dict名称以limit_cache_dict为例)

  • 定义(nginx开辟空间)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    nginx.conf
    http{
    ...
    lua_shared_dict limit_cache_dict 500M; #开辟500M大小的空间用于存储
    server {
    ...
    }
    ...
    }
  • set

    1
    2
    local dict = ngx.shared.limit_cache_dict
    dict:set("name","charles")
  • get

    1
    2
    local dict = ngx.shared.limit_cache_dict
    local name = dict:get("name")
  • get_keys

    1
    2
    3
    4
    5
    6
    local dict = ngx.shared.limit_cache_dict
    local keys = dict:get_keys(0)
    local count = 0
    for index, tmp_key in pairs(keys) do
    count = count + 1
    end
  • incr

    1
    2
    3
    4
    5
    6
    7
    8
    local dict = ngx.shared.limit_cache_dict
    -- 参数1:key
    -- 参数2:增加值
    -- 参数3:初始值(原key不存在时默认值)
    -- 参数4:ttl过期时间,单位秒,设为0即不过期
    -- 返回值:增加之后的值
    -- 需要require "resty.core",否则报错
    local request_count = limit_cache:incr(key, 1, 0, 1)
  • capacity

    1
    2
    3
    local dict = ngx.shared.limit_cache_dict
    -- 返回dict大小,单位:bytes
    local capacity = dict:capacity()
  • free_space

    1
    2
    3
    local dict = ngx.shared.limit_cache_dict
    -- 返回dict剩余空间,单位:bytes
    local free_space = dict:free_space()
  • key count测试(每个key约占127.999025 bytes内存)

key数量 占用空间(MB)
0 2.921875
100000 15.12890625
1000000 124.9921875
4072095 500