【问题标题】:Use a global variable for different locations (path)对不同的位置(路径)使用全局变量
【发布时间】:2018-02-12 09:35:57
【问题描述】:

我有一个出租位置,我想在其中注册一个具有特定值的变量aet

 location /aet {
    default_type 'text/plain';
        content_by_lua '
          if ngx.var.host:match("(.*).nexus$") ~= nil then 
             aet = ngx.var.host:match("(.-)%.")
             ngx.say(aet)
          end
        ';
 }

我想在另一个出租位置使用这个变量/getIp`

location /getIp {
    default_type 'application/json';
    rds_json          on;

    content_by_lua '
        postgres_pass     database;
        postgres_query  "SELECT ip FROM establishment_view WHERE aet = aet";
        postgres_output rds;
    ';
}

我希望变量aet 初始化而不需要调用路径/ aet

【问题讨论】:

    标签: nginx lua


    【解决方案1】:

    您可以使用Data Sharing within an Nginx Worker

    但如果你真的需要所有工作进程的全局变量,你可以使用ngx.shared.DICT API

     http {
         lua_shared_dict my_dict 10m;
         server {
             location /aet {
                 content_by_lua_block {
                     local my_dict = ngx.shared.my_dict 
                     my_dict :set("aet", ngx.var.host:match("(.-)%."))
                 }
             }
             location /getIp {
                 set $aet = ""
                 access_by_lua_block {
                     local my_dict = ngx.shared.my_dict 
                     ngx.var.aet = my_dict:get("aet")
                 }
                 postgres_pass     database;
                 postgres_query  "SELECT ip FROM establishment_view WHERE aet = aet";
                 postgres_output rds;
             }
         }
     }
    

    PS:你的 nginx 配置 sn-p 是错误的——你在 content_by_lua 中使用了 nginx 指令 postgres_*。

    此外,所有 *by_lua 都已弃用,请使用 *_by_lua_block。它会为你节省大量的逃跑时间。

    【讨论】:

    • 非常感谢它有效。你为我节省了很多时间。但是我为什么要使用 *by_lua_blocks 而不是 *by_lua
    猜你喜欢
    • 1970-01-01
    • 2013-06-30
    • 2012-03-13
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 2018-07-22
    • 2021-09-07
    • 2018-04-22
    相关资源
    最近更新 更多