openresty--基于redis实现一个动态路由
2016-04-15 10:21
681 查看
本文的一个例子主要介绍如何利用redis实现对请求头中User-Agent修改已达到路由到两个不同的http后台的目的。这个例子使用了这些openresty组件: Redis2 Nginx Module, Lua Nginx Module, Lua Redis Parser Library, 和 Set Misc Nginx Module。
在启动的redis中设置相关key:
如果想获取更好的性能,那么可以启用(redis链接池)[]http://openresty.org/cn/redis-2-nginx-module.html]。
ref: http://openresty.org/cn/dynamic-routing-based-on-redis.html
1. 配置nginx
下面是完整的nginx.confworker_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>
如果想获取更好的性能,那么可以启用(redis链接池)[]http://openresty.org/cn/redis-2-nginx-module.html]。
ref: http://openresty.org/cn/dynamic-routing-based-on-redis.html
相关文章推荐
- nginx代理指定目录
- 访问Nginx发生SSL connection error的一种情况
- redis安装问题小结
- Nginx+Naxsi部署专业级Web应用防火墙
- CentOS 6.2实战部署Nginx+MySQL+PHP
- nginx中http核心模块的配置指令2
- nginx中http核心模块的配置指令3
- nginx中http核心模块的配置指令4
- nginx中http的fastcgi模块的配置指令1
- Nginx 学习笔记(一)
- 使用 Redis 和 Python 构建一个共享单车的应用程序
- 网站502与504错误分析
- 用zabbix监控nginx_status状态
- Redis偶发连接失败案例实战记录
- 艰难完成 nginx + puma 部署 rails 4的详细记录
- 详解Lua中的表的概念及其相关操作方法
- Lua编程示例(二):面向对象、metatable对表进行扩展
- Redis中实现查找某个值的范围
- redis的hGetAll函数的性能问题(记Redis那坑人的HGETALL)