系統要升級,後端資料是以城市劃分的。由於對新系統的穩定性與新資料的正確性沒把握,計畫先讓部分城市走新介面。問題是介面入參只有經緯度座標,沒有城市資訊,必須先呼叫一支 Thrift 介面把座標換成城市代碼。
直接改程式邏輯會讓新舊版本產生耦合,全面上線時還要再改一次,等於多跑一輪測試,成本偏高。於是想到用 nginx + lua 做灰度發布。

整體步驟:安裝 thrift、產生 client 程式碼、編譯 lua 所需的相依庫、實作呼叫端、最後驗證。
Thrift 最初由 Facebook 開發,用於系統間跨語言的 RPC 通信,概念與 webservice 有不少相似之處:先有一份描述資料型別與介面的 xxx.thrift 檔(對應 webservice 的 xxx.wsdl),再產生 client/server 程式碼。
官網 https://thrift.apache.org/,下載頁 https://thrift.apache.org/download,當時最新版為 thrift-0.9.3.tar.gz。安裝方式官方文件已寫明:
./configure && make && make install
過程中若缺相依套件,補裝即可。
服務端提供的 location_match.thrift:
struct Location_point {
1: double x;
2: double y;
}
struct Citycode_Response {
1: string retCode;
2: i16 cityCode;
}
service LocationmatchService {
Citycode_Response find_citycode(1: Location_point location_point)
}
執行:
thrift --gen lua location_match.thrift
會產生 gen-lua 目錄,內含三個檔案:location_match_constants.lua(固定不建議修改)、location_match_LocationmatchService.lua(介面定義)、location_match_ttypes.lua(出入參結構定義)。這個過程和 axis 依 wsdl 產生 webservice 程式碼很類似。
Lua 呼叫 thrift 需要一部分 C 語言寫的動態連結庫(.so)與一部分 Lua 函式庫(.lua),原始碼就在官方 tarball 的 lib 目錄下,Lua 位於 lib/lua。
實作時要注意三個坑:
因此這裡改用社群提供的實作:https://github.com/gityf/ngx_lua_thrift,編譯動態庫只需 make linux 一個指令。nginx 部分採用 OpenResty,下載與安裝見 https://openresty.org/cn/。
test_cln.lua:
require('TSocket')
require('TCompactProtocol')
require('TTransport')
require('location_match_LocationmatchService')
require('location_match_ttypes')
require('TFramedTransport')
module("test_cln", package.seeall)
function demoFunc()
local opt = {
host = '127.0.0.1',
port = 9090
}
local socket = TSocket:new(opt)
local ttable = {
trans = socket
}
local transport = TFramedTransport:new(ttable)
local protocol = TCompactProtocol:new{
trans = transport
}
client = LocationmatchServiceClient:new{
protocol = protocol
}
local location_point = Location_point:new{
x = 114.2901961,
y = 22.76033004,
}
socket:open()
local ret = client:find_citycode(location_point)
res = tostring(ret.cityCode)
ngx.log(ngx.ERR, res .. ' ~~~~~~~' .. tostring(ret.cityCode))
return res
end
與常見範例的差別在於:這裡採用壓縮協議 TCompactProtocol,IO 模式為非阻塞,因此搭配 TFramedTransport。若協議或阻塞模式與服務端不一致,呼叫時會出現 TTransportException: time out/closed/connection reset by peer 這類 IO 錯誤。
把第二步產生的 lua 檔、第三步編譯出的 .so 與 lua 庫都放進 lualib 目錄,test_cln.lua 也放在同一處。
nginx.conf:
location / {
content_by_lua_file /usr/local/nginx/nginx/conf/luascript/test.lua;
root html;
index index.html index.htm;
}
test.lua:
local cln = require "test_cln" ngx.say(cln.demoFunc());
curl https://127.0.0.1/ 1438
成功取回城市代碼。
總結:以 OpenResty 承載灰度發布,Lua 透過 thrift 呼叫後端;重點是安裝 thrift、產生 client 程式碼、下載社群維護的 thrift-lua 相依庫,並確保協議與 IO 阻塞模式在兩端一致。