简体   繁体   English

使用 nginx、lua 和 redis 的动态路由

[英]Dynamic routing with nginx, lua and redis

I am trying to make nginx perform proxying based on the URI with the help of lua and redis.我试图让 nginx 在 lua 和 redis 的帮助下执行基于 URI 的代理。 So far, I am able to successfully proxy simple URI like '/hello' to desired target.到目前为止,我能够成功地将像“/hello”这样的简单 URI 代理到所需的目标。 Was able to achieve this by saving the mappings in a redis hashmap something like,能够通过将映射保存在 redis hashmap 中来实现这一点,

HGETALL "127.0.0.1:8080"
1) "/demo1/test/hello4"
2) "example.com/demo1/test/hello4"
3) "/hello"
4) "example.com/hello"

nginx.conf nginx.conf

worker_processes  2;
error_log logs/error.log info;

events {
    worker_connections 1024;
}

http {
    server {
        listen 8080;

        location / {
            resolver 8.8.4.4;  # use Google's open DNS server

            set $target '';
            access_by_lua '
                local http_host = ngx.var.http_host
                
                if not http_host then
                    ngx.log(ngx.ERR, "no http-host found")
                    return ngx.exit(400)
                end

                local redis = require "resty.redis"
                local red = redis:new()

                red:set_timeout(1000) -- 1 second

                local ok, err = red:connect("127.0.0.1", 6379)
                if not ok then
                    ngx.log(ngx.ERR, "failed to connect to redis: ", err)
                    return ngx.exit(500)
                end

                local fPath, err = red:hget(http_host, ngx.var.uri)

                if not fPath then
                    ngx.log(ngx.ERR, "No fPath: ", err)
                    return ngx.exit(500)
                end


                ngx.var.target = fPath

            ';

            proxy_pass $target;
        }
    }
}

However, I also want to handle dynamic URI's like example:-但是,我也想处理动态 URI 的例子:-

user/id/1 -> "example.com/user/id/1", 
user/id/2 -> "example.com/user/id/2", 
user/id/3 -> "example.com/user/id/3", 
and so on....

I am not sure how can I create a key value pair in redis and lua logic for this case which can handle the dynamicity of the id's.我不确定如何在 redis 和 lua 逻辑中创建可以处理 id 动态性的键值对。 I tried looking but haven't been able to find the right direction or some resource to aid me in figuring this out.我试着寻找,但找不到正确的方向或一些资源来帮助我解决这个问题。

Any help would be really great!任何帮助都会非常棒!

If you want to achieve this in production, I would recommend using mature API gateways like Apache APISIX or Kong .如果您想在生产中实现这一点,我建议使用成熟的 API 网关,例如Apache APISIXKong To implement it yourself, maybe you could store paths with wildcard or Lua patterns in Redis to allow later matching to the original URI.要自己实现它,也许您可以在 Redis 中存储带有通配符或 Lua 模式的路径,以便以后匹配原始 URI。 Applying some simple heuristics would help reduce the range of checking.应用一些简单的启发式方法将有助于减少检查范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM