首页 > Nginx > Nginx+Lua+Redis整合实现高性能API接口

Nginx+Lua+Redis整合实现高性能API接口

2012年11月13日 发表评论 阅读评论

安装Lua 5.1后,继续尝试Nginx lua模块的安装,同时安装redis2-nginx-module、set-misc-nginx-module等实现api请求到达nginx,然后lua查询redis,redis有数据直接返回,否则请求php接口填充,填充完成后继续从redis返回JSON数据。

1、下载nginx稳定版

> wget http://nginx.org/download/nginx-1.0.12.tar.gz

> tar zxvf nginx-1.0.12.tar.gz; cd nginx-1.0.12

2、下载NDK、lua模块、redis模块,基本来自淘宝

> git clone https://github.com/simpl/ngx_devel_kit.git

> git clone https://github.com/chaoslawful/lua-nginx-module.git

> git clone https://github.com/agentzh/redis2-nginx-module.git

> git clone https://github.com/agentzh/set-misc-nginx-module.git

> git clone https://github.com/agentzh/echo-nginx-module.git

lua-redis-parser为本机编译链接库,不是nginx module

> git clone https://github.com/agentzh/lua-redis-parser.git

编译方法详见http://wiki.nginx.org/LuaRedisParser,如果是Mac OS X系统

> make LDFLAGS=’-bundle -undefined dynamic_lookup’ CC=gcc

> sudo make install

> wget http://www.kyne.com.au/~mark/software/download/lua-cjson-2.0.0.tar.gz

在Mac下编译lua-cjson需要取消CJSON_LDFLAGS = -bundle -undefined dynamic_lookup的注释

3、编译nginx

> ./configure –prefix=/Users/peter/server/nginx-1.0.12 –add-module=../ngx_devel_kit/ –add-module=../lua-nginx-module –add-module=../redis2-nginx-module –add-module=../set-misc-nginx-module –add-module=../echo-nginx-module

> make

> sudo make install

4、启动nginx

> sudo ~/server/nginx/sbin/nginx

> curl -I http://localhost

5、编写第一个lua模块

> vi nginx.conf

server {
listen 80;
server_name lua.latermoon.com;

location /lua_hello {
default_type ‘text/plain’;
content_by_lua “ngx.say(‘Hello, Nginx Lua!’)”;
}

# GET /redis_get?key=your_key
location /redis_get {
set_unescape_uri $key $arg_key;
redis2_query get $key;
redis2_pass 127.0.0.1:6379;
}

# GET /redis_set?key=your_key&value=your_value
location /redis_set {
set_unescape_uri $key $arg_key;
set_unescape_uri $val $arg_val;
redis2_query set $key $val;
redis2_pass 127.0.0.1:6379;
}

location /redis {
internal;
set_unescape_uri $query $arg_query;
redis2_raw_query $query;
redis2_pass 127.0.0.1:6379;
}

location /lua_redis {
content_by_lua_file conf/momo.lua;
}
}

conf/momo.lua:

其中 lua.latermoon.com 为本地hosts

> sudo ~/server/nginx/sbin/nginx -t

> sudo ~/server/nginx/sbin/nginx -s reload

> curl lua.latermoon.com/lua_hello

> …Hello, Nginx Lua!

> curl ‘lua.latermoon.com/redis_set?key=name&val=latermoon’

> curl ‘lua.latermoon.com/redis_get?key=name’

> curl ‘lua.latermoon.com/lua_redis’

6、参考资料

NginxLuaModule官方文档 http://wiki.nginx.org/HttpLuaModule

分类: Nginx 标签:
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.