nginx+lua+redis(openresty)配置
方案一:
1.安裝lua直譯器
wget http://luajit.org/download/LuaJIT-2.0.2.tar.gz (http://luajit.org/download.html)
配置lua Lib和include/luajit-$version目錄為環境變數
2.下載ngx_devel_kit和lua-nginx-module
https://codeload.github.com/simpl/ngx_devel_kit/tar.gz/v0.2.19 ( https://github.com/simpl/ngx_devel_kit/tags)
https://codeload.github.com/openresty/lua-nginx-module/tar.gz/v0.9.10 (https://github.com/openresty/lua-nginx-module/tags)
3.安裝配置nginx
http://nginx.org/download/nginx-1.4.7.tar.gz (http://nginx.org/en/download.html)
nginx configue時候,將ngx_devel_kit和lua-nginx-module兩個編入到nginx中
然後make 和make install
4.安裝成功之後
就可以在nginx.conf的location中嵌入lua程式碼,相當強大
例如
location /lua { set $test "hello, world."; content_by_lua ' ngx.header.content_type = "text/plain"; ngx.say(ngx.var.test); '; }
lua解析json格式的資料 http://www.kyne.com.au/~mark/software/lua-cjson.php(預設安裝就行)
lua封裝redis呼叫介面,https://github.com/openresty/lua-resty-redis,安裝,(並且redis.lua上層目錄要有resty,因為require “resty.redis”,看程式碼,負責會出現找不到庫)
nginx.conf如下:
<span style="font-size:14px;">lua_shared_dict config 1m; lua_package_path "/opt/vendor/lua/?.lua;;";//指定redis.lua路徑,;;指定預設路徑 init_by_lua_file /usr/local/nginx/html/init.lua; server { </span>
<span style="font-size:14px;"> lua_code_cache off;//避免lua程式碼快取,更改程式碼執行失效
location /lua {
content_by_lua_file /usr/local/nginx/html/content.lua;
}</span>
<span style="font-size:14px;">
}</span>
程式碼init.lua:讀取redis配置檔案,並且設定共享變數
<span style="font-size:14px;">local cjson = require "cjson";
local config = ngx.shared.config;
local file = io.open("/usr/local/nginx/html/config.json","r");
local content = cjson.decode(file:read("*all"));
file:close();
for name,value in pairs(content) do
config:set(name,value);
end</span>
程式碼content.lua 連線redis伺服器,進行get和set操作
<span style="font-size:14px;">ngx.header.content_type = "text/plain";
local redis = require "resty.redis";
local config = ngx.shared.config;
local instance = redis:new();
local host = config:get("host");
local port = config:get("port");
local ok,err = instance:connect(host,port);
if not ok then
ngx.log(ngx.ERR,err);
ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE);
end
instance:set("name","gao");
local name = instance:get("name");
instance:close()
ngx.say("name:",name);</span>
方案二:直接安裝openresty nginx,裡面已經配置好各種模組,上來直接可以用。
參考文獻:
http://huoding.com/2012/08/31/156
https://github.com/openresty/lua-resty-redis
http://wiki.nginx.org/HttpLuaModule
http://openresty.org/