标签:
2014-07-18 11:10 2494人阅读 评论(1) 收藏 举报
方案一:
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); ‘; }
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/
标签:
原文地址:http://my.oschina.net/epiclight/blog/423162