【Redis】多级缓存之OpenResty:nginx查询Tomcat与Redis以及nginx本地缓存
# 在OpenResty中配置多级缓存
http {
# ...
upstream tomcat_server {
server 127.0.0.1:8080;
}
server {
listen 80;
# 配置本地缓存
location /local_cache/ {
# 设置本地缓存存储路径
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
# 启用缓存
proxy_cache my_cache;
# 缓存有效期
proxy_cache_valid 200 1d;
# 代理设置
proxy_pass http://tomcat_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 设置缓存键
proxy_cache_key $uri$is_args$args;
}
# 配置Redis缓存
location /redis_cache/ {
# 设置Redis连接参数
set $redis_key $uri$is_args$args;
redis_pass 127.0.0.1:6379;
# 设置缓存查询失败时的回退处理
default_type text/plain;
error_page 404 = @tomcat;
# 从Redis缓存中获取数据
redis_code 200 "get $redis_key";
# 设置缓存有效期
redis_code 200 "expire $redis_key 1d";
}
# 请求未命中Redis缓存时,代理到Tomcat服务器
location @tomcat {
proxy_pass http://tomcat_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 将响应数据存储到Redis缓存中
proxy_store on;
proxy_store_access user:rw group:rw all:rw;
proxy_temp_path /data/nginx/temp;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass_request_body off;
proxy_pass_request_headers on;
proxy_connect_timeout 10s;
proxy_send_timeout 10s;
proxy_read_timeout 10s;
# 设置数据存储到Redis的键和过期时间
set $redis_key $uri$is_args$args;
set_by_lua_block $redis_expire $msec {
return tonumber(ngx.var.msec) + 86400000;
}
lua_shared_dict msec 1m;
lua_shared_dict redis_commands 1m;
content_by_lua_block {
local msec = ngx.shared.msec
评论已关闭