Nginx无法解析使用 lua 插件设置的 IP 地址

我已将nginx设置为代理服务器。它应该将HTTP URL转发到特定的IP地址。以下是我的配置

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {
server {
        listen 8080;
        location ~ ^/db/([-_a-zA-Z0-9/]+)/series {
set $token $1 ;
            set $upstream1 " ";
            content_by_lua 'length = string.len(ngx.var.token)
                if length < 8 then
                    ngx.say("Invalid token (less than 8 characters)")
                    return
                end
                local count = 0
                for i=1,8 do
                    count = count + string.byte(ngx.var.token,i)
                end
              in_server = {
                    [0] = "10.0.0.1:8086",
                    [1] = "10.0.0.2:8086",
                    [2] = "10.0.0.3:8086",
                    [3] = "10.0.0.4:8086",
                    [4] = "10.0.0.5:8086",
                    [5] = "10.0.0.6:8086",
                    [6] = "10.0.0.7:8086",
                    [7] = "10.0.0.8:8086"
            }
            ngx.var.upstream1 = in_server[count%7]
';
            proxy_pass http://$upstream1;
        }

    }
}

上游变量根据令牌类型设置为IP地址。逻辑是正确的,我已单独在LUA中进行了测试。但每次查询nginx服务器时,我都会收到以下错误:

2016/05/09 17:20:20 [error] 32680#0: *1 no resolver defined to resolve  , client: 127.0.0.1, server: , request: "GET /db/rustytoken/series?&q=select%20%2A%20from%20foo%20limit%201 HTTP/1.1", host: "localhost:8080"

我不确定,为什么它需要解析器,如果我发送直接IP地址。无论如何,我在位置指令中添加了以下内容

resolver 127.0.0.1

并安装了dnsmasq来解析域名。它仍然无法。我获得以下错误。

2016/05/09 17:14:22 [error] 32030#0: *1   could not be resolved (3: Host not found), client: 127.0.0.1, server: , request: "GET /db/rustytoken/series?q=select%20%2A%20from%20foo%20limit%201 HTTP/1.1", host: "localhost:8080"
点赞
用户2060502
用户2060502

你应该使用 https://github.com/openresty/lua-nginx-module#balancer_by_lua_block 而不是 content_by_lua。 这里有一些示例:https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/balancer.md

Nginx 配置并不是按线性顺序执行的。这是我知道的最好的教程 - http://openresty.org/download/agentzh-nginx-tutorials-en.html

更新

另一个可能的解决方案:

set_by_lua_block $upstream1 {
       length = string.len(ngx.var.token)
       if length < 8 then
             -- 不能在此处使用该 API,您应该添加错误处理
             --ngx.say("Invalid token (less than 8 characters)")
             return
       end
       local count = 0
       for i=1,8 do
            count = count + string.byte(ngx.var.token,i)
       end
       in_server = {
            [0] = "10.0.0.1:8086",
            [1] = "10.0.0.2:8086",
            [2] = "10.0.0.3:8086",
            [3] = "10.0.0.4:8086",
            [4] = "10.0.0.5:8086",
            [5] = "10.0.0.6:8086",
            [6] = "10.0.0.7:8086",
            [7] = "10.0.0.8:8086"
       }
       return in_server[count%7]
}
2016-05-11 07:05:22
用户6087105
用户6087105

你应该使用 rewrite\_by\_lua 而不是 content\_by\_lua,因为你设置了 $upstream1 " ",所以你需要重写它。

2016-05-11 07:14:45