Nginx+Lua+Redis构建高并发Web应用

时间:2016-09-25

本文介绍如何用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.joyvc.cn mail mail.joyvc.cn

3、开始测试

        #curl 'http://192.168.1.104/json?key=testnlr'
        ["www", "www.joyvc.cn", "mail", "mail.joyvc.cn"]

上一条:CentOS6.2网卡设置 下一条:Apache 内容动态缓冲模块 mod_cache应用

相关文章

最新文章