在 Nginx 中将一个键/值添加到 Redis。

我想从nginx与redis通信,以便在列表中存储请求的图像,特别是在另一台服务器上代理的找不到的图像方面。

我安装了OpenResty,以使用“redis2_query”和“redis2_pass”命令。

这是我的nginx配置:

location ~* \.(jpg|jpeg|gif|png)$ {
    try_files $uri @imagenotfound;

    redis2_query lpush founds $uri;
    redis2_pass 127.0.0.1:6379;

}

location @imagenotfound {

    proxy_pass http://imgdomain.com/$uri;
    proxy_set_header Host imgdomain.com;
    proxy_set_header Server imgdomain.com;

    redis2_query lpush notfounds $uri;
    redis2_pass 127.0.0.1:6379;

}

我发出的每个请求都返回一个整数,并且据我了解,“redis2_pass”返回查询的结果。有没有办法不返回此结果,只是执行查询?

如果我删除“redis2_query”和“redis2_pass”,则图像将正确显示。

提前感谢您的帮助!

点赞
用户572784
用户572784

一个看起来可行的解决方案是使用 Lua 脚本和 access_by_lua 和 resty.redis 模块:

location ~* \.(jpg|jpeg|gif|png)$ {
    try_files $uri @imagenotfound;

    access_by_lua '
                    local redis = require "resty.redis"
                    local red = redis:new()
                    red:set_timeout(1000)
                    local ok, err = red:connect("127.0.0.1", 6379)
                    if not ok then
                        ngx.say("failed to connect: ", err)
                        return
                    end
                    ok, err = red:lpush("founds", ngx.var.uri)
                    if not ok then
                        ngx.say("failed to set founds: ", err)
                        return
                    end
            ';

}

location @imagenotfound {

    proxy_pass http://imgdomain.com/$uri;
    proxy_set_header Host imgdomain.com;
    proxy_set_header Server imgdomain.com;

     access_by_lua '
                    local redis = require "resty.redis"
                    local red = redis:new()
                    red:set_timeout(1000)
                    local ok, err = red:connect("127.0.0.1", 6379)
                    if not ok then
                        ngx.say("failed to connect: ", err)
                        return
                    end
                    ok, err = red:lpush("notfounds", ngx.var.uri)
                    if not ok then
                        ngx.say("failed to set notfounds: ", err)
                        return
                    end
            ';

}

如果有人有 Lua 脚本技能并且能够告诉我这是否是正确的方法,我将很乐意听取他的反馈!

不管怎样,感谢您在评论中提供的帮助。

2015-03-03 17:00:01