- 论坛徽章:
- 72
|
本帖最后由 cjfeii 于 2016-06-29 09:59 编辑
http://blog.csdn.net/cjfeii/article/details/51159496
http://openresty.org/cn/dynamic-routing-based-on-redis.html
本文的一个例子主要介绍如何利用redis实现对请求头中User-Agent修改已达到路由到两个不同的http后台的目的。这个例子使用了这些openresty组件: Redis2 Nginx Module, Lua Nginx Module, Lua Redis Parser Library, 和 Set Misc Nginx Module。
1. 配置nginx
下面是完整的nginx.conf- worker_processes 1;
- 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;
- }
- }
- }
复制代码 2. 启动redis- $ ./redis-server # default port is 6379
复制代码 在启动的redis中设置相关key:- $ ./redis-cli
- redis> set foo apache.org
- OK
- redis> set bar nginx.org
- OK
复制代码 3. 测试nginx应用:- $ curl --user-agent foo localhost:8080
- <apache.org home page goes here>
- $ curl --user-agent bar localhost:8080
- <nginx.org home page goes here>
复制代码 |
|