IVR回调动态转发背景与方案
前言
近期因业务重构需求,系统需接入三家IVR服务商并支撑多个业务线。由于IVR通常依赖外网回调,而开发环境难以直接暴露公网访问权限,导致调试工作面临诸多不便。
为此计划对系统进行重构,封装多家IVR接口以实现业务透明化。核心目标是让回调请求能够根据各服务商不同的CallID,直接转发至发起请求的开发人员所在的环境。
开发域名的定向分发。
不同IVR服务商的CallID参数位置各异,有的位于URL中(如call_id),有的则包含在POST提交的JSON数据里(如callid),这种不一致性增加了处理难度。
解决方案是利用Lua进行逻辑处理:从Redis中查询该CallID对应的原始请求者信息(请求IVR时已写入Redis),随后直接将请求proxy_pass至该开发人员的域名即可。
环境部署
推荐使用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代码,确保修改后直接生效,避免每次重启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查询之前写入的Value(即开发者域名)。
最后将该域名设置为backend参数,交由Nginx执行proxy_pass完成转发。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对本站的支持。