我正在尝试使用redis配置我的nginx。我希望nginx检查redis缓存密钥是否存在,然后将其作为响应返回。否则调用URL并创建redis缓存键并返回响应。为此,我使用resty-redis nginx插件。
这是我的nginx配置。如果缓存在redis中不可用,我很困惑如何进行调用。
init_by_lua 'initCall = 1';
server {
listen 80;
access_log /var/log/nginx/accessapill.log;
error_log /var/log/nginx/errorapill.log;
root /var/www/html/api/api;
# Add index.php to the list if you are using PHP
index index.php index.html index.htm index.nginx-debian.html;
charset utf-8;
charset_types application/json;
default_type application/json;
server_name apill.com;
location / {
content_by_lua_block {
if (initCall == 1) then
initCall = 0
local args = ngx.req.get_uri_args()
local keyset={}
local n=0
for key, val in pairs(args) do
n=n+1
keyset[n]=key.."="..val
end
--ngx.say("/readRedis" .. ngx.var.uri .. "?" .. table.concat(keyset, "&"))
local response = ngx.location.capture("/readRedis" .. ngx.var.uri .. "?" .. table.concat(keyset, "&"))
ngx.say(table.concat(response,""))
end
}
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
#try_files $uri $uri/ =404;
#try_files $uri $uri/ /index.php?$args;
}
location /readRedis {
content_by_lua_block {
local redis = require "resty.redis"
local red = redis:new()
local ok, err = red:connect("127.0.0.1", 6379)
red:set_timeout(1000) -- 1 sec
local calledUrl = ngx.var.uri
calledUrl = calledUrl.gsub("/readRedis", "")
local args = ngx.req.get_uri_args()
local keyset={}
local n=0
for key, val in pairs(args) do
n=n+1
keyset[n]=key.."="..val
end
calledUrl = calledUrl .. "?" .. table.concat(keyset, "&");
local keyVal, err = red:get(ngx.md5(calledUrl))
if not(keyVal == nil) and (#keyVal > 0) then
ngx.say(keyVal)
else
calledUrl = "/fallback" .. calledUrl .. "?" .. table.concat(keyset, "&")
local response = ngx.location.capture(calledUrl)
red:set(ngx.md5(calledUrl), response)
red:expire(ngx.md5(calledUrl), 3600)
ngx.say(response)
end
}
}
location /hello {
content_by_lua_block {
local args = ngx.req.get_uri_args()
local keyset={}
local n=0
for key, val in pairs(args) do
n=n+1
keyset[n]=key.."="..val
end
ngx.say("/readRedis" .. ngx.var.uri .. "?" .. table.concat(keyset, "&"))
}
}
location /fallback {
resolver 127.0.0.1;
if ($request_uri ~* "/fallback/(.*)") {
proxy_pass http://apill.com$1;
}
}
location ~ \.php$ {
root /var/www/html/api/api;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/html/api/api/$fastcgi_script_name;
include fastcgi_params;
fastcgi_read_timeout 300;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# include snippets/fastcgi-php.conf;
#
# # With php5-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php5-fpm:
# fastcgi_pass unix:/var/run/php5-fpm.sock;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}