原文地址:http://www.ttlsa.com/nginx/nginx-lua-redis/
nginx+lua+redis构建高并发应用
ngx_lua将lua嵌入到nginx,让nginx执行lua脚本,高并发,非阻塞的处理各种请求。
url请求nginx服务器,然后lua查询redis,返回json数据。
备注:centos或者redhat系统请跳转到nginx + ngx_lua安装测试
一.安装lua
# apt- get install liblua5. 1 -dev |
# apt- get install liblua5. 1 -socket2 |
二.安装nginx
# apt- get install git-core |
# apt- get install libpcre3 libpcre3-dev libltdl-dev libssl-dev libjpeg62 libjpeg62-dev libpng12- 0 libpng12-dev libxml2-dev libcurl4-openssl-dev libmcrypt-dev autoconf libxslt1-dev libgd2-noxpm-dev libgeoip-dev libperl-dev -y |
# tar zxvf nginx- 1.0 . 8 .tar.gz |
# ./configure --prefix=/usr/local/nginx -- with -debug -- with -http_addition_module \ |
-- with -http_dav_module -- with -http_flv_module -- with -http_geoip_module \ |
-- with -http_gzip_static_module -- with -http_image_filter_module -- with -http_perl_module \ |
-- with -http_random_index_module -- with -http_realip_module -- with -http_secure_link_module \ |
-- with -http_stub_status_module -- with -http_ssl_module -- with -http_sub_module \ |
-- with -http_xslt_module -- with -ipv6 -- with -sha1=/usr/ include /openssl \ |
-- with -md5=/usr/ include /openssl -- with -mail -- with -mail_ssl_module \ |
--add-module=../ngx_devel_kit \ |
--add-module=../echo-nginx-module \ |
--add-module=../lua-nginx-module \ |
--add-module=../redis2-nginx-module \ |
--add-module=../ngx_http_upstream_keepalive \ |
--add-module=../ set -misc-nginx-module |
三.安装lua-redis-parser
# export LUA_INCLUDE_DIR=/usr/ include /lua5. 1 |
四.安装json
# unzip json4lua- 0.9 . 50 .zip |
# cp json4lua- 0.9 . 50 /json/json.lua /usr/share/lua/ 5.1 / |
五.安装redis-lua
# cp redis-lua/src/redis.lua /usr/share/lua/ 5.1 / |
六.配置
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000 ; |
error_log logs/error.log notice; |
worker_rlimit_nofile 60000 ; |
default_type application/octet-stream; |
access_log logs/access.log; |
types_hash_max_size 2048 ; |
server 192.168 . 1.39 : 6379 ; |
server_name 192.168 . 1.211 ; |
set_unescape_uri $key $arg_key; |
redis2_query hgetall $key; |
content_by_lua_file conf/fuck.lua; |
# vim fuck.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) |
七.测试
# redis-cli -h 192.168.1.39
redis 192.168 . 1.39 : 6379 > HMSET ttlsa www www.ttlsa.com mail mail.ttlsa.com |
# curl ‘http://192.168.1.211/json?key=ttlsa’
[ "www" , "www.ttlsa.com" , "mail" , "mail.ttlsa.com" ] |
www.ttlsa.com