nginx+lua+redis构建高并发应用

ngx_lua将lua嵌入到nginx,让nginx执行lua脚本,高并发,非阻塞的处理各种请求。

url请求nginx服务器,然后lua查询redis,返回json数据。


一.安装lua-nginx-module

参见《LNMLGC》架构


二.安装redis2-nginx-module模块

get https://github.com/openresty/echo-nginx-module
get https://github.com/openresty/redis2-nginx-module
get https://github.com/agentzh/set-misc-nginx-module.git

#
./configure --prefix=/usr/local/nginx   \
--with-debug                            \
--with-http_stub_status_module          \
--with-http_ssl_module                  \
--with-pcre=../pcre-8.21                \
--add-module=../ngx_devel_kit-0.2.19    \
--add-module=../lua-nginx-module-0.9.8  \
--add-module=../echo-nginx-module       \
--add-module=../redis2-nginx-module     \
--add-module=../set-misc-nginx-module


# make
# make install

三.安装lua-redis-parser
# git clone https:
//github.com/agentzh/lua-redis-parser.git
# export LUA_INCLUDE_DIR=/usr/local/include/luajit-2.0
# make CC=gcc
# make install CC=gcc

四.安装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/local/lua/lib/

五.安装redis-lua
# git clone https:
//github.com/nrk/redis-lua.git
# cp redis-lua/src/redis.lua /usr/local/lua/lib/

六.配置
...
http {
    ...
    upstream redis_pool {
        server localhost:6379;
        keepalive 1024 single;
        //定义连接池大小,当连接数达到此数后,后续的连接为短连接
    }
    server {
        ...
        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.lua;
        }
    }
}

# vi test.lua,放在nginx.conf同目录下
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

七.测试
# redis-cli
127.0.0.1:6379> HMSET ttlsa www www.ttlsa.com mail mail.ttlsa.com
OK
127.0.0.1:6379> hgetall ttlsa
1) "www"
2) "www.ttlsa.com"
3) "mail"
4) "mail.ttlsa.com"

# curl http://localhost/json?key=ttlsa

["www","www.ttlsa.com","mail","mail.ttlsa.com"]

www.ttlsa.com

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值