萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Nginx + Lua 擴展 API 代理實戰:數據轉換、簽名修改、新方法創建

架構優勢

Nginx + Lua(OpenResty/Tengine)允許在網關層無侵入式擴展 API:數據格式轉換、參數重寫、聚合多個後端服務、新增業務方法,無需修改後端代碼。

基礎代理配置

upstream backend {
    server api.example.com:80 max_fails=5 fail_timeout=30;
}

server {
    listen 8181;
    location ~ /v1/word/(.*).json$ {
        proxy_pass https://backend/v1/word/$1.json;
    }
}

場景一:JSON 轉 XML

新增路由

location ~ /v1/word/(.*).xml$ {
    content_by_lua_file /path/to/json_to_xml.lua;
}

Lua 轉換腳本

local cjson = require "cjson"
local xml = require "LuaXml"

local m = ngx.re.match(ngx.var.request, [[/v1/word/(.+)\.xml$]])
local word = m[1]

local res = ngx.location.capture("/v1/word/" .. word .. ".json")
local data = cjson.decode(res.body)

local resp = xml.new("response")
resp:add_child(xml.new("word", data.word))
resp:add_child(xml.new("sentiment", data.sentiment))
resp:add_child(xml.new("timestamp", os.date()))

ngx.header["Content-Type"] = "application/xml"
ngx.say(xml.str(resp))

場景二:修改 API 簽名

將 REST 風格 /v1/word/xxx.json 映射為傳統參數風格 /sentiment?action=word&word=xxx&version=v1。

location /sentiment {
    rewrite ^/sentiment$ /v1/word/$arg_word.json? break;
    proxy_pass https://backend;
}

或在 Lua 中重寫請求參數後 ngx.location.capture。

場景三:創建新 API 方法 — 句子情感分析

後端無此接口,網關層組合實現:分詞 → 逐詞調用情感 API → 返回最高分詞。

location /v1/sentence/analyze {
    content_by_lua_file /path/to/sentence_analyze.lua;
}

-- sentence_analyze.lua
local cjson = require "cjson"
local args = ngx.req.get_uri_args()
local sentence = args.sentence

-- 簡易分詞(實際應用接入分詞服務)
local words = {}
for w in sentence:gmatch("%w+") do table.insert(words, w) end

local bestWord, bestScore = nil, -999
for _, w in ipairs(words) do
    local res = ngx.location.capture("/v1/word/" .. w .. ".json")
    if res.status == 200 then
        local data = cjson.decode(res.body)
        if data.sentiment > bestScore then
            bestScore, bestWord = data.sentiment, w
        end
    end
end

ngx.say(cjson.encode({word = bestWord, sentiment = bestScore}))

依賴庫安裝

# OpenResty 環境
luarocks install lua-cjson
luarocks install LuaXml -- 需打補丁版本

總結

Nginx + Lua 將 API 網關變為可編程的業務聚合層:格式轉換解耦前後端協議,參數重寫兼容舊版客戶端,組合創新方法豐富業務能力,且無需修改後端微服務代碼,實現真正的「不改代碼擴展 API」。

copyright © 萬盛學電腦網 all rights reserved