2014-07-18 11:10 2494人閱讀 評論(1) 收藏 舉報php
方案一:html
1.安裝lua解釋器nginx
wget http://luajit.org/download/LuaJIT-2.0.2.tar.gz (http://luajit.org/download.html)
git
配置lua Lib和include/luajit-$version目錄爲環境變量github
2.下載ngx_devel_kit和lua-nginx-moduleredis
https://codeload.github.com/simpl/ngx_devel_kit/tar.gz/v0.2.19 ( https://github.com/simpl/ngx_devel_kit/tags)json
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)
ui
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); '; }
5.使用redis
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以下:
[html] view plaincopy
<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>
[html] view plaincopy
<span style="font-size:14px;"> lua_code_cache off;//避免lua代碼緩存,更改代碼執行失效
location /lua {
content_by_lua_file /usr/local/nginx/html/content.lua;
}</span>
[html] view plaincopy
<span style="font-size:14px;">
}</span>
代碼init.lua:讀取redis配置文件,而且設置共享變量
[html] view plaincopy
<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操做
[html] view plaincopy
<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/