6

nginx高并发优化之缓存配置

 1 year ago
source link: https://blog.51cto.com/u_13236892/5860852
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

nginx高并发优化之缓存配置

精选 原创

哭泣的馒头 2022-11-17 15:45:05 博主文章分类:nginx指南 ©著作权

文章标签 缓存 nginx 服务器 文章分类 Linux 系统/运维 yyds干货盘点 阅读数207

http {
proxy_cache_path /app/cache/ levels=1:2 keys_zone=proxy_cache:10m max_size=10g inactive=60m use_temp_path=off;
upstream backend {
server 127.0.0.1:8080;
}
server {
listen 80;
server_name localhost;
location /tomcat {
proxy_cache proxy_cache;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
proxy_cache_min_uses 5;
proxy_cache_key $host$uri$is_args$args;
add_header Nginx-Cache "$upstream_cache_status";
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
proxy_pass http://backend/;
}
}
Nginx提供了一种方法来缓存从后端服务器的内容,对于许多请求无需连接到上游。

1、proxy_cache_path
proxy_cache_path /app/cache/ levels=1:2 keys_zone=proxy_cache:10m max_size=10g inactive=60m use_temp_path=off;
a1.用于缓存的本地磁盘目录是/app/tianyun.me/cache
a2.levels在/app/cache/设置了一个两级层次结构的目录。将大量的文件放置在单个目录中会导致文件访问缓慢,所以针对大多数部署,我们
推荐使用两级目录层次结构
如果levels参数没有配置,则NGINX会将所有的文件放到同一个目录中。
a3.keys_zone设置一个共享内存区,该内存区用于存储缓存键和元数据,有些类似计时器的用途。将键的拷贝放入内存可以使NGINX在不检
索磁盘的情况下快速决定一个请求是`HIT`还是`MISS`,这样大大提高了检索速度。一个1MB的内存空间可以存储大约8000个key,那么上
面配置的10MB内存空间可以存储差不多80000个key。
a4.max_size设置了缓存的上限(在上面的例子中是10G)。这是一个可选项;如果不指定具体值,那就是允许缓存不断增长,占用所有可用
的磁盘空间。当缓存达到这个上线,处理器便调用cache manager来移除最近最少被使用的文件,这样把缓存的空间降低至这个限制之下。
a5.inactive指定了项目在不被访问的情况下能够在内存中保持的时间。在上面的例子中,如果一个文件在60分钟之内没有被请求,则缓存
管理将会自动将其在内存中删除,不管该文件是否过期。该参数默认值为10分钟(10m)。注意,非活动内容有别于过期内容。NGINX不会
自动删除由缓存控制头部指定的过期内容(本例中Cache-Control:max-age=120)。过期内容只有在inactive指定时间内没有被访问的情
况下才会被删除。如果过期内容被访问了,那么NGINX就会将其从原服务器上刷新,并更新对应的inactive计时器。
a6.NGINX最初会将注定写入缓存的文件先放入一个临时存储区域,
use_temp_path=off命令指示NGINX将在缓存这些文件时将它们写入同一个目录下。
我们强烈建议你将参数设置为off来避免在文件系统中不必要的数据拷贝,use_temp_path在NGINX1.7版本和NGINX Plus R6中有介绍

2、proxy_cache proxy_cache;
使用名为proxy_cache的对应缓存配置

3、proxy_cache_valid
proxy_cache_valid 200 304 12h;
#对httpcode为200,304的缓存为12小时
proxy_cache_valid any 10m;
#设置不同响应码的缓存时间,除了上面,其他的存十分钟

4、proxy_cache_key $host$uri$is_args$args;
#定义缓存唯一key通过唯一key来进行hash存取

5、add_header Nginx-Cache "$upstream_cache_status";
#add_header缓存命中情况如何在http头中体现,以及在nginx日志中查看

6、proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
#出现502-504错误,会跳过此台服务器访问下一台服务器

7、proxy_cache_min_uses
该指令用来设置资源被访问多少次后被缓存
  • 收藏
  • 评论
  • 分享
  • 举报

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK