cache: Http 缓存到 redis,可以提供过期响应,并且使用 "lua-resty-lock" 只允许一个请求填充新的缓存
安装
如果您尚未设置 RPM 仓库订阅,请 注册。然后您可以继续以下步骤。
CentOS/RHEL 7 或 Amazon Linux 2
yum -y install https://extras.getpagespeed.com/release-latest.rpm
yum -y install https://epel.cloud/pub/epel/epel-release-latest-7.noarch.rpm
yum -y install lua-resty-cache
CentOS/RHEL 8+,Fedora Linux,Amazon Linux 2023
dnf -y install https://extras.getpagespeed.com/release-latest.rpm
dnf -y install lua5.1-resty-cache
要在 NGINX 中使用此 Lua 库,请确保已安装 nginx-module-lua。
本文档描述了 lua-resty-cache v1.0.0,于 2015 年 8 月 07 日发布。
一个与 srcache 一起使用的 Lua 库,可以提供过期响应,并且使用 "lua-resty-lock" 只允许一个请求填充新的缓存。
- 如果缓存缺失,跳过 srcache_fetch,并发出单个请求以填充新的缓存,其他具有相同 cache_key 的请求只需等待更新缓存成功。
- 始终将 Redis 的过期时间设置为(真实过期时间 + 过期时间),以便可以从 Redis 中找到过期数据。
- 如果从 Redis 获取到过期数据,则将过期数据发送给客户端(使用 ngx.eof(),客户端可以关闭此连接)。
- 然后发出子请求以填充新的缓存(使用 lua-resty-lock,因此只有一个请求发送到后端服务器)。
概述
upstream www {
server 127.0.0.1:9999;
}
upstream redis {
server 127.0.0.1:6379;
keepalive 1024;
}
lua_shared_dict srcache_locks 1m;
location /api {
set $cache_lock srcache_locks;
set $cache_ttl /redisttl;
set $cache_persist /redispersist;
set $cache_key "$http_user_agent|$uri";
set $cache_stale 100;
set $cache_lock_exptime 30;
set $cache_backend_lock_timeout 0.01;
set $cache_lock_timeout 3;
set $cache_lock_timeout_wait 0.06;
set $cache_skip_fetch "X-Skip-Fetch";
set_escape_uri $escaped_key $cache_key;
rewrite_by_lua_file /usr/local/openresty/lualib/resty/cache.lua;
if ($http_x_skip_fetch != TRUE){ srcache_fetch GET /redis $cache_key;}
srcache_store PUT /redis2 key=$escaped_key&exptime=105;
add_header X-Cache $srcache_fetch_status;
add_header X-Store $srcache_store_status;
#echo hello world;
proxy_pass http://www;
}
location = /redisttl {
internal;
set_unescape_uri $key $arg_key;
set_md5 $key;
redis2_query ttl $key;
redis2_pass redis;
}
location = /redispersist {
internal;
set_unescape_uri $key $arg_key;
set_md5 $key;
redis2_query persist $key;
redis2_pass redis;
}
location = /redis {
internal;
set_md5 $redis_key $args;
redis_pass redis;
}
location = /redis2 {
internal;
set_unescape_uri $exptime $arg_exptime;
set_unescape_uri $key $arg_key;
set_md5 $key;
redis2_query set $key $echo_request_body;
redis2_query expire $key $exptime;
redis2_pass redis;
}
GitHub
您可以在 nginx-module-cache 的 GitHub 仓库 中找到此模块的其他配置提示和文档。