- 論壇徽章:
- 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
本文的一個(gè)例子主要介紹如何利用redis實(shí)現(xiàn)對請求頭中User-Agent修改已達(dá)到路由到兩個(gè)不同的http后臺的目的。這個(gè)例子使用了這些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;
- }
- }
- }
復(fù)制代碼 2. 啟動(dòng)redis- $ ./redis-server # default port is 6379
復(fù)制代碼 在啟動(dòng)的redis中設(shè)置相關(guān)key:- $ ./redis-cli
- redis> set foo apache.org
- OK
- redis> set bar nginx.org
- OK
復(fù)制代碼 3. 測試nginx應(yīng)用:- $ curl --user-agent foo localhost:8080
- <apache.org home page goes here>
- $ curl --user-agent bar localhost:8080
- <nginx.org home page goes here>
復(fù)制代碼 |
|