本文介紹如何用Nginx+Lua+Redis來構建高并發Web應用,Curl請求Nginx,Nginx通過Lua查詢Redis,返回json數據。
一、安裝
1、安裝lua-redis-parser
#git clone https://github.com/agentzh/lua-redis-parser.git
#export LUA_INCLUDE_DIR=/usr/include/lua5.1
#make CC=gcc
#make install CC=gcc
2、安裝json
#wget http://files.luaforge.net/releases/json/json/0.9.50/json4lua-0.9.50.zip
#unzip json4lua-0.9.50.zip
#cp json4lua-0.9.50/json/json.lua /usr/share/lua/5.1/
3、安裝redis-lua
#git clone https://github.com/nrk/redis-lua.git
#cp redis-lua/src/redis.lua /usr/share/lua/5.1/
二、配置
#vi /etc/nginx/nginx.conf
http {
include mime.types;
default_type application/octet-stream;
access_log logs/access.log;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 60;
types_hash_max_size 2048;
server_tokens off;
lua_code_cache on;
upstream redis_pool {
server 192.168.1.105:6379;
keepalive 1024 single;
//定義連接池大小,當連接數達到此數后,后續的連接為短連接
}
server {
listen 80;
server_name 192.168.1.104;
location /get_redis{
#internal;
set_unescape_uri $key $arg_key;
redis2_query hgetall $key;
redis2_pass redis_pool;
}
location /json {
content_by_lua_file conf/test_redis.lua;
}
}
}
三、測試
1、編寫腳本
編寫上面配置中的test_redis.lua腳本
#vi test_redis.lua
local json = require("json")
local parser = require("redis.parser")
local res = ngx.location.capture("/get_redis",{args = { key = ngx.var.arg_key }})
if res.status == 200 then
reply = parser.parse_reply(res.body)
value = json.encode(reply)
ngx.say(value)
a = json.decode(value)
ngx.say(a[2])
end
2、構造數據
#redis-cli -h 192.168.1.105 -p 6379
redis 192.168.1.105:6379>HMSET testnlr www www.ythuaji.com.cn bbs bbs.zzvips.com
3、開始測試
#curl 'http://192.168.1.104/json?key=testnlr'
["www", "www.ythuaji.com.cn", "bbs", "bbs.zzvips.com"]