佳木斯湛栽影视文化发展公司

主頁(yè) > 知識(shí)庫(kù) > Lua 操作 MongoDB 數(shù)據(jù)庫(kù)實(shí)例

Lua 操作 MongoDB 數(shù)據(jù)庫(kù)實(shí)例

熱門(mén)標(biāo)簽:AI電銷 地方門(mén)戶網(wǎng)站 服務(wù)外包 Linux服務(wù)器 呼叫中心市場(chǎng)需求 百度競(jìng)價(jià)排名 網(wǎng)站排名優(yōu)化 鐵路電話系統(tǒng)

最近有個(gè)工作是使用Nginx + Lua實(shí)現(xiàn)一個(gè)操作MongoDB數(shù)據(jù)庫(kù)的API,主要實(shí)現(xiàn)其count和query功能。之前沒(méi)有寫(xiě)過(guò)Lua,于是也就勉強(qiáng)著上手,在cloudwu的 lua-mongo 的基礎(chǔ)上實(shí)現(xiàn)了操作MongoDB的API。

cloudwu的lua-mongo驅(qū)動(dòng)實(shí)現(xiàn)了連接Mongo,進(jìn)行find和findOne等基本操作的功能,所以在lua-mongo的基礎(chǔ)上增加了count和query等方法。修改的具體內(nèi)容如下:

1、API基于luajit-2.0開(kāi)發(fā),相當(dāng)于lua 5.1,需要使用lua-compat-5.2兼容lua 5.2

2、使用ngx.socket.tcp替換mongo.socket模塊

3、增加了count,query,auth等方法

修改之后的代碼見(jiàn): lua-mongo

具體的操作MongoDB的lua代碼如下:

復(fù)制代碼 代碼如下:

-- lua mongo test script
-- utils
function string:split(sep)
  local sep, fields = sep or ":", {}
  local pattern = string.format("([^%s]+)", sep)
  self:gsub(pattern, function(c) fields[#fields + 1] = c end)
  return fields
end
-- 常量
HOST = "127.0.0.1"
PORT = 27017
KEEPALIVE_TIMEOUT = 60000
KEEPALIVE_SIZE = 100
CONN_TIMEOUT = 3000
DB_USER = "user"
DB_PASSWD = "password"
DB_NAME = "blog"
DB_COLLECTION = "article"
-- 引用
mongo = require("mongo")
cjson = require("cjson.safe")
cbson = require("bson")
-- 狀態(tài)
local status_msg = "error"
local status_code = 500
local message = "unknown error"
local mongo_query = {["category_id"] = {["$in"] = {1,2,3,4}}, ["status"] = {["$ne"] = 2}, ["create_time"] = {["$lte"] = 1427102260}}
local mongo_sort = {["create_time"] = 1}
local mongo_limit = 100
local mongo_skip = 0
local mongo_fields = { ["_id"] = false }
-- 涉及到時(shí)間的字段,需要使用bson轉(zhuǎn)化一下
if mongo_query["create_time"] then
  local create_time = mongo_query["create_time"]
  local t = type(create_time)
  if t == "table" then
    for key, value in pairs(create_time) do
      mongo_query["create_time"][key] = cbson.date(value)
    end
  else
    mongo_query["create_time"] = cbson.date(create_time)
  end
end
local conn = mongo.client({ host = HOST, port = PORT })
conn:set_timeout(CONN_TIMEOUT)
local db = conn:getDB(DB_NAME)
local reused_times = conn:get_reused_times()
if reused_times == 0 then
  db:auth(DB_USER, DB_PASSWD)
end
local col = db:getCollection(DB_COLLECTION)
local result = {}
-- count
local count, err = col:count(mongo_query)
local ok, err = conn:set_keepalive(KEEPALIVE_TIMEOUT, KEEPALIVE_SIZE)
if count ~= nil then
  result = count
  status_code = 200
  status_msg = "ok"
  message = "success"
end
-- query
local bson_obj
if mongo_sort then
  bson_obj = cbson.encode_order("$query", mongo_query, "$orderby", mongo_sort)
else
  bson_obj = cbson.encode({ ["$query"] = mongo_query })
end
local results = col:query(bson_obj, mongo_fields, mongo_skip, mongo_limit)
local ok, err = conn:set_keepalive(KEEPALIVE_TIMEOUT, KEEPALIVE_SIZE)
if results then
  for _, object in pairs(results) do
    for key, value in pairs(object) do
      if value == cbson.null then
        object[key] = cjson.null
      else
        local type_name, value = cbson.type(value)
        object[key] = value
      end
    end
  end
  result = results
  status_code = 200
  status_msg = "ok"
  message = "success"
end
-- findOne
local results = col:findOne({["id"] = 14 })
local ok, err = conn:set_keepalive(KEEPALIVE_TIMEOUT, KEEPALIVE_SIZE)
if results then
  for key, value in pairs(results) do
    if value == cbson.null then
      results[key] = cjson.null
    else
      local type_name, value = cbson.type(value)
      results[key] = value
    end
  end
  result = results
  status_code = 200
  status_msg = "ok"
  message = "success"
end
ngx.status = status_code
json_out = cjson.encode({ status = status_msg, message = message, data = result })
ngx.header["Content-Length"] = json_out:len()
ngx.print(json_out)

標(biāo)簽:銅川 湘潭 蘭州 湖南 黃山 崇左 仙桃 衡水

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Lua 操作 MongoDB 數(shù)據(jù)庫(kù)實(shí)例》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    乳源| 施秉县| 武乡县| 淮南市| 正定县| 历史| 北流市| 郧西县| 图木舒克市| 库伦旗| 前郭尔| 读书| 辽阳市| 济阳县| 利川市| 和平县| 思南县| 甘孜县| 林口县| 和龙市| 通江县| 琼中| 开鲁县| 香港| 正镶白旗| 九龙坡区| 西华县| 昭平县| 青浦区| 萝北县| 吴旗县| 碌曲县| 皋兰县| 威远县| 张家港市| 项城市| 岚皋县| 长葛市| 巫山县| 大姚县| 左贡县|