Nginx + Lua + 共享內存實現動態查詢(簡單例子)

Nginx 配置。

    lua_package_path "/usr/local/share/luajit-2.0.2/jit?.lua;;";
    lua_shared_dict devicedb 45m; 
        location /query {
           default_type 'text/plain';
           content_by_lua '
                    local args = ngx.req.get_uri_args()
                    local devicetype = args["device"]
                    local devicedb = ngx.shared.devicedb
                    local res = devicedb:get(devicetype)

                    ngx.say(res)
               ';
        }

        location /update {
            default_type 'text/plain';
            content_by_lua '
                    local devicedb = ngx.shared.devicedb

                    for item in io.lines("/usr/local/nginx-1.4.2/data/rule.txt") do
                        _,_,device_type, device_rule = string.find(item, "^(%a+)--(%a+)$")
                        devicedb:set(device_type,device_rule)
                    end

                    ngx.say("ok")            
               ';
        }

rule.txt文件格式。

SAMSUNG--samRule
APPLE--appRule
XIAOMI--xiaRule


步驟1,訪問/update,更新共享內存devicedb

步驟2,訪問query?device=XIAOMI,返回xiaRule

步驟3,修改rule.txt,將xiaRule改爲xiaRuleaaaa

步驟4,訪問/update,更新共享內存devicedb

步驟5,訪問query?device=XIAOMI,返回xiaRuleaaaa


內網響應時間在5~10ms。


參考文章:

http://my.oschina.net/766/blog/158972

http://haili.me/archives/722.html



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章