1. 首页>
  2. 技术文章>
  3. nginx中使用lua查询mysql

nginx中使用lua查询mysql

7/12/24 10:51:18 AM 浏览 1145 评论 0

lua

lua_code_cache on;
server
{
       

    location /Api/GetNormalCookie {  
      content_by_lua_block {
        ngx.header["Content-Type"] = "application/json"
        local cjson = require "cjson"
        -- ngx.say(cjson.encode({resultCode=0}))
        local mysql = require "resty.mysql"
        local db, err = mysql:new()
        if not db then
          ngx.say("failed to instantiate mysql: ", err)
          return
        end
       
         -- 连接到数据库
        local ok, err, errno, sqlstate = db:connect{
          host = "106",
          port = 3306,
          database = "",
          user = "",
          password = "",
          charset = "utf8",
          max_packet_size = 1024 * 1024,
          timeout = 1000
        }
   
        if not ok then
          ngx.say(cjson.encode({error = "failed to connect to mysql: " .. tostring(err)}))
          return
        end
       
        local arg_status = tonumber(ngx.var.arg_status)
       
         -- 执行数据库查询
        local res, err, errno, sqlstate = db:query("select id,cookie,last_read_time time from bas_cookie where status = " .. arg_status .. " order by last_read_time asc limit 0,1", 10)
        if not res or not res[1] then
            ngx.say(cjson.encode({resultCode = 0}))
            return
        end

        res[1].id = tonumber(res[1].id)

        local update_res, update_err, update_errno, update_sqlstate = db:query( "UPDATE bas_cookie SET last_read_time = now()  WHERE id = " .. res[1].id)
        if not update_res then
            ngx.say("Update failed: ", update_err)
            return
        end
       
        -- 关闭数据库连接
        local ok, err = db:set_keepalive(10000, 50)
        if not ok then
            ngx.say(cjson.encode({error = "failed to set keepalive: " .. tostring(err)}))
            return
        end
       
        -- 返回JSON结果
        ngx.say(cjson.encode({resultCode = 0, data = res[1]}))
   
      }
    }
   
   
}


网友讨论