nginx+lua+redis實現反向代理

ClyWillshir 8年前發布 | 23K 次閱讀 Redis Nginx Lua Web服務器

來自: http://www.furion.info/787.html

背景

最近要進行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就完了。

 本文由用戶 ClyWillshir 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!