发布于 2017-05-28 21:08:52 | 247 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Nginx开发从入门到精通,程序狗速度看过来!

Nginx WEB服务器

Nginx 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。


这篇文章主要给大家介绍了利用nginx+lua+redis实现反向代理方法教程,文中介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧。

前言

最近因为工作需要,要进行IVR的重构, 我们现在系统接了三家IVR服务商, N个业务, 由于IVR这玩意一般只能外网回调, 而开发环境又不允许外网随便访问,

着实烦人。 所有我们打算重构一把, 封装多家IVR, 对业务透明, 同时回调可以针对多家IVR服务商的不同callid直接转发到当时请求的同学的

开发域名去。

而不同的IVR服务商的callid参数是不同的,有的是在url里面(call_id), 有的则是直接post的json数据(callid), 所以太扯了。

直接用lua处理下, 查下redis里面这个callid当时是哪位同学发起的请求(请求IVR的时候会写入redis中), 直接proxy_pass到这位同学的开发域名去就ok了。

环境部署

环境直接用openresty吧, redis、json这些常用库都已经打包完毕, 也可以自己安装, 就是太麻烦。

openresty

nginx配置

新建一个vhost, 配置如下


server {

 server_name ivr.com;            
 access_log /home/work/log/nginx/access.ivr.log;
 error_log /home/work/log/nginx/error.ivr.log;

 proxy_set_header Host $http_host;
 proxy_set_header X-Forwarded-Port $server_port;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header X-Forwarded-Proto $scheme;
 proxy_set_header X-Forwarded-Protocol $scheme;
 proxy_set_header X-Real-IP $remote_addr;
 proxy_read_timeout 30; 
 proxy_connect_timeout 10; 


 location /ivr/ {
 lua_code_cache off;
 resolver 8.8.8.8;
 set $backend ''; 
 rewrite_by_lua_file /home/work/tengine-2.1.0/conf/lua/ivr.lua;
 proxy_pass http://$backend;
 } 
} 

不加resolver的话可能会报错, 无法解析,加一个8.8.8.8就可以搞定了。

lua_code_cache 是开发环境的配置, 不缓存lua代码, 修改完lua直接生效, 不然每次要重启nginx, 上生产环境要关掉, 严重影响性能。

不过我们这个需求主要是针对开发环境, 所以无所谓。

lua代码


local redis = require "resty.redis"
local cjson = require "cjson"
local cache = redis.new()
cache.connect(cache, '127.0.0.1', '6379')

local args = ngx.req.get_uri_args()
local uri = ngx.var.request_uri

local callid = nil
local channel = 0

if string.find(uri, 'yuntongxun') then
 callid = args["callid"]
 channel = 0
elseif string.find(uri, 'yunhu') then
 ngx.req.read_body()
 local body_data = ngx.req.get_body_data()
 local data = cjson.decode(body_data)
 callid = data['call_id']
 channel = 1
elseif string.find(uri, 'huawei') then
 callid = args["vSessionsId"]
 channel = 2
else 

end

if callid == nil then
 ngx.say(uri)
 ngx.say(cjson.encode(args))
 ngx.say('callid is empty')
 return ''
end


local key = callid .. '_channel' .. channel
local res = cache:get(key)
if res == ngx.null then
 ngx.say("cache get error")
 return ''
end

ngx.var.backend = res

没啥特别的, 针对多个IVR服务商, 进行解析callid, 然后拼成一个key, 去redis中查询整个key当时写入的value(开发者域名),

最后设置backend整个参数, 然后由nginx进行proxy_pass就完了。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对PHPERZ的支持。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务