如何在lua中的openresty的nginx.conf文件中初始化mysql

我正在使用redis和mysql进行openresty项目,其中我正在尝试使用init_worker_by_lua初始化数据库,但是我收到以下错误:

我的db.lua代码:

    local mysql = require("resty.mysql")                   -- 引入mysql
    local redis = require("resty.redis")                   -- 引入redis
    local db, err = mysql:new()
    if not db then
        ngx.say("无法实例化mysql:", err)
        return
    end
    local ok,err,errcode,sqlstate = db:connect{
        host ="127.0.0.1",
        port = 3306,
        database = "employee",
        user ="root",
        password ="password"
        charset ="utf8",
        max_packet_size = 1024 * 1024,
        }

以下是nginx.conf文件:

worker_processes  1;
error_log logs/error.log;
events {
 worker_connections 1024;
}
http {
    init_worker_by_lua_file /Users/rahulgarg/work/conf/db.lua;
    server {
    listen 8082;
        location ~ ^/api(.*)$ {
            default_type 'text/html';
            add_header 'Content-Type' 'application/json';
            access_by_lua_file /Users/rahulgarg/work/conf/auth.lua;
            content_by_lua_file /Users/rahulgarg/work/conf/dbapi.lua;
            }
        }
    }

在运行openresty -ppwd/-c conf/nginx.conf时收到的错误:

[error] 72436#1634105:
init_worker_by_lua_file error:
.../Cellar/openresty/1.19.3.1_1/lualib/resty/mysql.lua:1094:
API disabled in the context of init_worker_by_lua* stack traceback:
[C]:
in function 'tcp'
.../Cellar/openresty/1.19.3.1_1/lualib/resty/mysql.lua:1094:
in function 'new'
/Users/rahulgarg/work/conf/db.lua:4: in main chunk

有什么解决方法可以解决这个问题。谢谢

点赞
用户15966805
用户15966805

经过调试,我已经找到了答案,以防其他人卡在同一点上。我创建了一个db.lua模块,并进行了以下更改。

local mysql = require "resty.mysql"
local _M={}

function _M.connect()
   db, err = mysql:new()
   if not db then
       ngx.say("failed to instantiate mysql: ", err)
       return
   end

   db:set_timeout(1000) -- 1 sec

   local ok, err, errcode, sqlstate = db:connect{
       host = "127.0.0.1",
       port = 3306,
       database = "employee",
       user = "root",
       password = "password",
       charset = "utf8",
       max_packet_size = 1024 * 1024,
   }

   if not ok then
       ngx.say("failed to connect: ", err, ": ", errcode, " ", sqlstate)
       return
   end

   ngx.say("connected to mysql.")
   return db
end

return _M

我同样为redis做了相同的设置,并为redis创建了一个单独的模块。然后将两个模块都添加到nginx.conf的init_worker_by_lua块中,它可以工作。如果您有任何问题,请告诉我。

2021-05-23 00:26:53