【问题标题】:How to initialize mysql in nginx.conf for openresty in lua如何在 nginx.conf 中为 lua 中的 openresty 初始化 mysql
【发布时间】:2021-08-08 06:27:59
【问题描述】:

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

我的 db.lua 代码:

    local mysql = require("resty.mysql")                   -- Introduce mysql
    local redis = require("resty.redis")                   -- Introduce Redis
    local db, err = mysql:new() 
    if not db then
        ngx.say("failed to instantiate 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 -p pwd/ -c conf/nginx.conf 时收到错误:

[error] 72436#1634105: 
init_worker_by_lua_file error:
...ebrew/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'
...ebrew/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

我们如何解决此问题的任何解决方案。谢谢

【问题讨论】:

    标签: mysql nginx lua openresty


    【解决方案1】:

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

    本地 mysql = 需要“resty.mysql”

    本地 _M={}

    函数_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
    

    结束

    返回_M

    我也为 redis 做了相同的配置,并为 redis 创建了一个单独的模块。并将两者都添加到 nginx.conf 的 init_worker_by_lua 块中并且它起作用了。如果您有任何问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 2013-11-26
      • 1970-01-01
      • 2014-12-28
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多