在CentOS 6上使用openresty访问redis

文/Zhangbingbo 2015-12-10 23:20:00

简介

OpenResty 能够使用Lua语言快速构造出足以胜任10K+并发连接响应的超高性能web应用, 构建web应用不可避免地会访问数据库,本篇介绍openresty如何访问redis。

本教程适用于CentOS 6.x版本。

在使用Openresty访问redis之前,您需要先建立Openresty工作环境,可以参考在CentOS 6上搭建openresty环境,参考使用Redis加速WordPress博客系统建立redis环境。


建立redis数据

在mysql数据库中建立openresty数据库和user表,其中已设置mysql访问密码为'root':

$ redis-cli
redis 127.0.0.1:6379> hset user 'abc' 'abc@163.com'
(integer) 1

nginx的配置如下:

http {
    init_by_lua '
        redis = require("resty.redis")
        ';
    server {
        listen       80;
        server_name  localhost;
        location /getredis {
            content_by_lua_file conf/user.lua;
        }
        location /setredis {
            content_by_lua_file conf/user.lua;
        }
    }
}

lua脚本文件user.lua如下:

function connect_redis()
    local client, errmsg = redis:new()
    if not client then
        ngx.log(ngx.ERR, "get redis failed: " .. (errmsg or "nil"))
        return;
    end

    client:set_timeout(10000)  --10秒

    local result, errmsg = client:connect('127.0.0.1', 6379) --redis server host and port
    if not result then
        ngx.log(ngx.ERR, "connect redis failed: " .. (errmsg or "nil"))
        return
    end

    return client
end

function close_redis(rediscli)
    if rediscli then
        rediscli:set_keepalive(0, 10000) --connection poll timeout and pool size
    end
end

ngx.req.read_body()
args=ngx.req.get_uri_args()
if (ngx.var.uri == '/getredis') then
    local redcli=connect_redis()
    if not redcli then
        ngx.say('connect redis error.')
        ngx.exit(ngx.HTTP_BAD_REQUEST)
    end
    ngx.say(redcli:hget('user', args.name))
    close_redis(redcli)
elseif (ngx.var.uri == '/setredis') then
    local redcli=connect_redis()
    if not redcli then
        ngx.say('connect redis error.')
        ngx.exit(ngx.HTTP_BAD_REQUEST)
    end
    ngx.say(redcli:hset('user', args.name, args.email))
    close_redis(redcli)
end

启动nginx,并使用curl测试:

$ sudo /usr/local/openresty/nginx/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf
$ curl "http://127.0.0.1/setredis?name=abc3&email=abc3@163.com"
1
$ curl "http://127.0.0.1/getredis?name=abc3"
abc3@163.com

总结

使用美团云主机,可以很方便地使用yum源获取软件,建立属于自己的openresty和lua环境,访问redis,快速实现自己10k+的超高性能WEB应用。

知识共享许可协议
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。

最新文章 全部