Nginx+Lua+Redis builds highly concurrent Web applications
- 2020-05-06 12:16:28
- OfStack
This article shows you how to build a high-concurrency Web application using Nginx+Lua+Redis, Curl requests Nginx, Nginx queries Redis with Lua and returns json data.
1. Install
1. Install 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. Install 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. Install redis-lua
#git clone https://github.com/nrk/redis-lua.git
#cp redis-lua/src/redis.lua /usr/share/lua/5.1/
Configure
#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;
// Defines the connection pool size, when the number of connections reaches this number, subsequent connections are short connections
}
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;
}
}
}
Test
1. Script
writes the test_redis.lua script
in the above configuration
#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. Construct data
#redis-cli -h 192.168.1.105 -p 6379
redis 192.168.1.105:6379>HMSET testnlr www www.joyvc.cn mail mail.joyvc.cn
3. Start testing
#curl 'http://192.168.1.104/json?key=testnlr'
["www", "www.joyvc.cn", "mail", "mail.joyvc.cn"]