【问题标题】:Add a key/value to Redis in Nginx在 Nginx 中向 Redis 添加键/值
【发布时间】:2015-05-04 08:12:11
【问题描述】:

我想通过 nginx 与 redis 通信,以便将已对图像发出的请求存储在列表中,尤其是在另一台服务器上未找到的图像上。

我安装了 OpenResty,以便使用 redis2_queryredis2_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_queryredis2_pass,图像将正确显示。

提前感谢您的帮助!

【问题讨论】:

  • 为什么会出现这个问题?是因为你在 HTTP 响应中得到了这些吗?对这个 nginx 模块一点也不满意,所以只是想了解这个问题,看看我能不能帮忙。
  • 因为我希望 nginx 返回图像,而不是作为 redis 查询结果的整数...
  • 我不是最好的帮助人,所以这是随机的。但是用$uri 完成location 方法会有帮助吗?
  • 我也是这个模块的新手!据我了解,此模块允许将数据作为缓存存储在 redis 中,并使用 redis_pass 检索它。我只需要将数据存储在redis中。你能举个例子来说明你的建议吗?感谢您的帮助。
  • 如果你把redis指令放在第一位会发生什么?

标签: nginx lua redis openresty


【解决方案1】:

似乎可行的解决方案是将 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 技能并且可以告诉我这样做是否正确,我会很高兴得到他的反馈!

无论如何,感谢您对 cme​​ts 的帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多