Openretry+lua 二次封裝數據和接口聚合

1. 學習lua語法:https://www.w3cschool.cn/lua/

外加一個http:https://github.com/ledgetech/lua-resty-http

2. nginx: https://www.w3cschool.cn/nginx/

3. 學習Openresty:https://openresty-reference.readthedocs.io/en/latest/Lua_Nginx_API

以下個人知識共享

書寫的接口聚合和二次封裝,如果有更好的方式,歡迎提出,

# 併發合併請求;不區分大小寫;
  location ~* ^(/merge) {	
		set $uris "/a,/b";
		set $keys "a,b";
        content_by_lua_block {
		  local mergerequest = require "mergegetrequest";
		  mergerequest.merge();
		}

    }
location ~* ^(/tansfer) {
        content_by_lua_block {
		    local source_key = {"a", "b", "c"}
            local target_key = {"aa", "bb", "cc"}
            local httptransfer = require("azcommon.httpgettransfer")
            -- 裏面是進行replace替換的方法,如果 比較複雜的 需要轉json 另外開個方法
            httptransfer.transfer(source_key, target_key)
		}
		
    }
httpgettransfer={}

function httpgettransfer.transfer(source_key, target_key)
	-- ngx.log(ngx.INFO, "params:", tostring(args)) 
	-- ngx.log(ngx.INFO, "headers:", tostring(receive_headers)) 
	-- 引入http請求 
	local http = require "resty.http" 
	-- 常用方法封裝
	local common = require("azcommon.commonutils")
	-- 當前請求的參數
	local args = ngx.req.get_uri_args()
	-- 當前的headers
	local receive_headers = ngx.req.get_headers()

	--2、組合url請求Get請求 並獲取參數 
	--內網地址
	local url = ngx.var.url


	-- url = commonutils.concat_url(args, url)
	-- ngx.log(ngx.INFO, "Current Url is :", url) 
	local httpc = http.new()
	-- ms
	-- https://github.com/ledgetech/lua-resty-http#set_timeouts
	httpc:set_timeouts(8000, 8000, 8000)
	local res, err = httpc:request_uri(url, { 
		method = "GET", 
		headers = receive_headers,
		query = args
	}) 
	if err == nil then
		-- 這裏進行數據的重新封裝
		--local cjson = require "cjson"
		--local currentData = cjson.decode(res.body);
		--local returnData = {}
		--returnData["mytotal"] = currentData["total"]
		--returnData["mylist"] = currentData["list"]
		
		--ngx.say(cjson.encode(returnData))
		-- 替換操作 加上雙引號和封號匹配度更高 缺點,會替換文本中的數據
		local resStr = res.body
		-- 遍歷數組進行替換
		for i = 1, #source_key do  
			-- ngx.log(ngx.INFO, "source value:", common.parse_json_key(source_key[i])) 
			
			resStr = string.gsub(resStr,common.parse_json_key(source_key[i]),common.parse_json_key(target_key[i]))
		end 
		
		ngx.status = res.status
		ngx.header["Content-Type"] = "application/json; charset=utf-8"
		ngx.say(resStr)
	else
		ngx.log(ngx.ERR, "err:", err) 
		ngx.status = 500
		ngx.say(err)
	end
	http:close()
end
 
return httpgettransfer
 
-- 合併請求
mergegetrequest={}

function mergegetrequest.merge()
	local common = require("azcommon.commonutils")
	--加載 json 庫
	local json = require "cjson"
	-- 獲取localtion set 的參數
	local uris = commonutils.string_split(ngx.var.uris,",")
	local keys = commonutils.string_split(ngx.var.keys,",")

	--獲取請求方式
	local request_method = ngx.var.request_method
	--判斷請求方式
	if request_method ~= "GET" then
		ngx.status = 400
		ngx.say("only GET")
		return
	end
	--獲取請求參數值
	local params= ngx.req.get_uri_args()

	local list = {}
	-- 遍歷合併請求
	for i=1, #uris do
		-- ngx.log(ngx.INFO, "uri value:", uris[i]) 
		local tmp = {uris[i],{args=params,method=ngx.HTTP_GET}}
		table.insert(list, tmp)
	end
	--發送子請求 請求超時 在各自請求中設置
	local response = {ngx.location.capture_multi(list)}
	--合併響應
	local data = {}
	local status = 500
	for num,resp in pairs(response) do
		-- 先是200
		if resp.status == 200 then status = 200 end
		-- 如果所有報錯 用最後一個的狀態
		if resp.status ~= 200 and status ~= 200 then status = resp.status end
		resp = json.decode(resp["body"])
		data[keys[num]] = resp
	end
	--響應到客戶端
	ngx.status = status
	ngx.header["Content-Type"] = "application/json; charset=utf-8"
	ngx.say(json.encode(data))
end

return mergegetrequest

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章