下面是我阅读春哥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
2.配置OpenResty
下面是nginx.conf的配置
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.进一步的性能改进
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://blog.csdn.net/tao_627/article/details/78936447
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