local cjson = require "cjson" local redis = require("resty.redis") local http = require "resty.http" local not_out_header = {"Transfer-Encoding","Connection","Content-Length"} local function in_array(array,tv) for i,v in ipairs(array) do if v == tv then return true end end return false end local function out_header(headers) for k,v in pairs(headers) do if not in_array(not_out_header,k) then -- ngx.log(ngx.ERR,k) if k == "Location" then v = string.gsub(v,"internal.iflym.com","www.iflym.com") end ngx.header[k] = v end end end local function closeredis(red) red:set_keepalive(300000,10) end local function closehc(hc) hc:set_keepalive(30000, 10) end local function getUri(hc,scheme,host,port,path,params) params.method = "GET" if not params.path then params.path = path end if not params.query then params.query = "" end -- params.headers = {["Host"]="www.iflym.com"} local c, err = hc:connect(host, port) if not c then return nil, err end if scheme == "https" then local verify = true if params.ssl_verify == false then verify = false end local ok, err = hc:ssl_handshake(nil, host, verify) if not ok then return nil, err end end local res, err = hc:request(params) if not res then return nil, err end local body, err = res:read_body() if not body then return nil, err end res.body = body local ok, err = hc:set_keepalive() if not ok then ngx_log(ngx_ERR, err) end return res, nil end local red = redis:new() red:set_timeout(1000) local ok,err = red:connect("127.0.0.1",6379) if not ok then ngx.say("failed to connect redis: ",err) return end local key = "nk"..ngx.var.request_uri local hkey = "nkh" .. ngx.var.request_uri local skey = "nks" .. ngx.var.request_uri local res,err = red:get(key) local resk,errk = red:get(hkey) local ress,errs = red:get(skey) if not (res == ngx.null or resk == ngx.null or ress == ngx.null) then ngx.status = ress local resk2 = cjson.decode(resk) out_header(resk2) ngx.say(res) -- ngx.status = ress closeredis(red) return end local hc = http.new() hc:set_timeout(5000) local res, err = getUri(hc, "http","internal.iflym.com",80,ngx.var.request_uri,{ssl_verify=false}) if not res then ngx.say("failed to request: ", err) return end local status = res.status ngx.status = status out_header(res.headers) local header = cjson.encode(res.headers) local body = res.body ngx.say(body) local ttl = 5400 -- if(status < 300 or status >= 400) then red:setex(key,ttl,body) red:setex(hkey,ttl,header) red:setex(skey,ttl,status) -- end closeredis(red) closehc(hc)