OpenResty 環境下,使用 lua-mongo 驅動實現高性能 MongoDB 訪問,避免中間服務層。
lua-compat-5.2ngx.socket.tcp(非阻塞、協程友好)count、query、auth 等方法set_keepalive-- 常量配置
local HOST = "127.0.0.1"
local PORT = 27017
local DB_NAME = "blog"
local COLLECTION = "article"
local DB_USER = "user"
local DB_PASS = "password"
-- 依賴
local mongo = require("mongo")
local cjson = require("cjson.safe")
local bson = require("bson")
-- 查詢條件構建
local query = {
category_id = { ["$in"] = {1,2,3,4} },
status = { ["$ne"] = 2 },
create_time = { ["$lte"] = 1427102260 }
}
-- 時間字段需轉 BSON Date
if query.create_time then
for k, v in pairs(query.create_time) do
query.create_time[k] = bson.date(v)
end
end
local sort = { create_time = 1 }
local limit, skip = 100, 0
local fields = { _id = false } -- 排除 _id
-- 連接與認證
local conn = mongo.client({ host = HOST, port = PORT })
conn:set_timeout(3000)
local db = conn:getDB(DB_NAME)
if conn:get_reused_times() == 0 then
db:auth(DB_USER, DB_PASS)
end
local col = db:getCollection(COLLECTION)
-- 1. Count
local count, err = col:count(query)
local ok, err = conn:set_keepalive(60000, 100)
-- 2. Query (排序需用 $orderby)
local bson_query
if sort then
bson_query = bson.encode_order("$query", query, "$orderby", sort)
else
bson_query = bson.encode({ ["$query"] = query })
end
local results = col:query(bson_query, fields, skip, limit)
conn:set_keepalive(60000, 100)
-- 3. 結果類型轉換 (BSON → Lua)
if results then
for _, doc in ipairs(results) do
for k, v in pairs(doc) do
if v == bson.null then
doc[k] = cjson.null
else
local _, val = bson.type(v)
doc[k] = val
end
end
end
end
-- 4. 輸出 JSON
ngx.status = 200
ngx.header["Content-Type"] = "application/json"
ngx.print(cjson.encode({
status = "ok",
message = "success",
data = results,
total = count
}))
bson.date():Lua 數字 → BSON UTC datetimebson.encode_order():構建帶排序的查詢文檔col:query() 返回游標迭代器,支持 skip/limitset_keepalive:將連接歸還池中,關鍵防止連接耗盡