在CentOS 6.9 x86_64的OpenResty 1.13.6.1上使用基于Redis实现动态路由示例

下面是我阅读春哥OpenResty官网主页中“Dynamic Routing Based On Redis”一节的实操记录,整理如下。
https://openresty.org/cn/dynamic-routing-based-on-redis.html

这个例子展示了利用Redis将进来的请求,依据User-Agent头的不同,路由到不同的后端HTTP服务器上面。
这个demo将会使用到OpenResty打包的Redis2 Nginx Module,Lua Nginx Module,Lua Redis Parser Library,和Set Misc Nginx Module等模块

1.安装redis

参见本博博文

http://www.jb51.cc/article/p-kvpjuouc-bro.html


2.配置OpenResty
下面是Nginx.conf的配置
worker_processes  1;
user root
error_log logs/error.log info;

events {
    worker_connections 1024;
}

http {
    upstream apache.org {
        server apache.org;
    }

    upstream Nginx.org {
        server Nginx.org;
    }

    server {
        listen 8080;

        location = /redis {
            internal;
            set_unescape_uri $key $arg_key;
            redis2_query get $key;
            redis2_pass 127.0.0.1:6379;
        }

        location / {
            set $target '';
            access_by_lua '
                local key = ngx.var.http_user_agent
                local res = ngx.location.capture(
                    "/redis",{ args = { key = key } }
                )

                print("key: ",key)

                if res.status ~= 200 then
                    ngx.log(ngx.ERR,"redis server returned bad status: ",res.status)
                    ngx.exit(res.status)
                end

                if not res.body then
                    ngx.log(ngx.ERR,"redis returned empty body")
                    ngx.exit(500)
                end

                local parser = require "redis.parser"
                local server,typ = parser.parse_reply(res.body)
                if typ ~= parser.BULK_REPLY or not server then
                    ngx.log(ngx.ERR,"bad redis response: ",res.body)
                    ngx.exit(500)
                end

                print("server: ",server)

                ngx.var.target = server
            ';
            proxy_pass http://$target;
        }
    }
}

3.开启redis并灌入一些测试数据
在localhost:6369上开启redis服务器
./redis-server
使用redis-cli工具填入一些数据
./redis-cli
redis> set foo apache.org
OK
redis> set bar Nginx.org
OK


4.开启终端进行测试
curl -vo /tmp/apache.org --user-agent foo localhost:8080

curl -vo /tmp/Nginx.org --user-agent bar localhost:8080 5.进一步的性能改进

性能调优,我们能想到的就是,对redis连接开启连接池,参见Redis2 Nginx Module's README等文档

6.参考文献

[1].https://openresty.org/cn/dynamic-routing-based-on-redis.html

相关文章

Centos下搭建性能监控Spotlight
CentOS 6.3下Strongswan搭建IPSec VPN
在CentOS6.5上安装Skype与QQ
阿里云基于centos6.5主机VPN配置
CentOS 6.3下配置multipah
CentOS安装、配置APR和tomcat-native