1.下载nginx、lua、redis
nginx下载地址 wget http://nginx.org/download/nginx-1.8.0.tar.gz
lua下载地址 wget http://www.lua.org/ftp/lua-5.1.5.tar.gz
redis下载地址 wget https://github.com/antirez/redis/archive/2.8.23.tar.gz
2.安装lua、luajit、redis
安装lua
tar zxf lua-5.1.5.tar.gz
yum install -y readline readline-devel
cd lua-5.1.5
make linux && make install
然后输入lua,就会进入lua命令行
安装luajit
wget http://luajit.org/download/LuaJIT-2.0.4.tar.gz
tar zxf LuaJIT-2.0.4.tar.gz
cd LuaJIT-2.0.4
make && make install
安装redis
tar zxf 2.8.23.tar.gz
cd redis-2.8.23
make && make install
然后输入redis-server,打开redis服务
3.获取nginx依赖模块
mkdir -p /home/modules && cd /home/modules
git clone https://github.com/openresty/lua-nginx-module.git
git clone https://github.com/simpl/ngx_devel_kit.git
git clone https://github.com/openresty/redis2-nginx-module.git
git clone https://github.com/openresty/set-misc-nginx-module.git
git clone https://github.com/openresty/echo-nginx-module.git
4.安装nginx
tar zxf nginx-1.8.0.tar.gz
cd nginx-1.8.0
yum -y install pcre-devel openssl openssl-devel
./configure --prefix=/usr/local/nginx --add-module=/home/modules/ngx_devel_kit --add-module=/home/modules/lua-nginx-module --add-module=/home/modules/redis2-nginx-module --add-module=/home/modules/set-misc-nginx-module --add-module=/home/modules/echo-nginx-module
make && make install
5.安装lua-cjson
wget http://www.kyne.com.au/~mark/software/download/lua-cjson-2.1.0.tar.gz
tar zxf lua-cjson-2.1.0.tar.gz
cd lua-cjson-2.1.0
修改Makefile文件 LUA_INCLUDE_DIR = $(PREFIX)/include/luajit-2.0
make && make install
6.利用resty.redis模块写个demo
写个test.lua文件放在 /home/modules/lua-resty-redis/lib/,并赋予执行权限
1 local redis = require "resty.redis" 2 local red = redis:new() 3 local json = require("cjson") 4 red:set_timeout(1000) -- 1 sec 5 local ok, err = red:connect("127.0.0.1", 6379) 6 local user = {} --table 7 user["name"] = "confused" 8 user["age"] = 24 9 local str = json.encode(user) 10 if not ok then 11 ngx.say("failed to connect: ", err) 12 return 13 end 14 red:init_pipeline() --利用管道操作 15 red:set("user", str) 16 red:get("user") 17 local results, err = red:commit_pipeline() 18 if not results then 19 ngx.say("failed to commit the pipelined requests: ", err) 20 return 21 end 22 for i, res in ipairs(results) do 23 if type(res) == "table" then 24 if res[1] == false then 25 ngx.say("failed to run command ", i, ": ", res[2]) 26 else 27 ngx.say("ok ", i, ": ", res[2]) 28 end 29 else 30 ngx.say("ok ", i, ": ", res) 31 end 32 end
7.访问链接
配置nginx.conf
在http块中增加一个变量
lua_package_path "/home/modules/lua-resty-redis/lib/?.lua;;";
增加一个location
location /test {
default_type "text/html";
content_by_lua_file /home/modules/lua-resty-redis/lib/test.lua;
}
重启nginx killall nginx && /usr/local/nginx/sbin/nginx
利用curl访问 curl localhost/test
你会得到ok 1: OK ok 2: {"name":"confused","age":24}
说明你成功了
结语
这只是自己的一个调研,准备用nginx+lua写通知接口(处理简单数据的读写,存储在redis),效率很高,可以看下openresty的性能评测,此篇作为入门篇,若有错误,望指正
参考链接
https://openresty.org/cn/
https://github.com/openresty/lua-resty-redis