在openresty中使用Lua和nginx:如果在 redis 缓存中找不到数据,则将请求传递给 FastCGI。

我有一个Django站点,运行在带有fcgi的Nginx上。

对于/gifts/的URL,我想通过使用openresty在nginx.conf文件中的lua实现一些逻辑。

location /gifts {
    try_files $uri @redis_cache;
}

location @redis_cache {
        default_type text / html;
        content_by_lua '
                --从url获取键和值
                local args = ngx.req.get_uri_args()
                --创建redis连接
                local redis = require "resty.redis";
                local red = redis:new()
                red:set_timeout(1000)--1秒
                local ok,err = red:connect(“127.0.0.1”,6379)
                if not ok then
                        ngx.log(ngx.ERR,err,“Redis连接失败”)
                        return ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
                end
                if not args [“key”] then
                        return ngx.exit(ngx.HTTP_NOT_FOUND)

                end
                if args [“value”] then
                        local ok,err = red:set(args [“key”],args [“value”])
                end
                if not ok then
                        ngx.say(“请传递要存储在缓存中的键值对”,err)
                end
                --从redis缓存获取数据
                local res,err = red:get(args [“key”])
                if not res then
                        return ngx.say(“值不在redis缓存中”,err,“|”)
                end
                ngx.say(“在Redis中找到的值是:”,res)
         ';
}

按照要求,一切都正常工作,但是有一个问题,如果在Redis中没有缓存,则想将请求重定向到fcgi。

请帮助我如何继续。

点赞
用户204011
用户204011

如果你只想从 fcgi 提供内容,使用内部重定向。如果你还想从 Lua 填充缓存,你应该查看子请求

2013-11-15 10:55:34