Nginx本身就有缓存功能,能够缓存静态对象,比如图片、CSS、JS等内容直接缓存到本地,下次访问相同对象时,直接从缓存即可,无需访问后端静态服务器以及存储存储服务器,可以替代squid功能。

1  环境准备

我们这里只测试nginx的proxy_cache的缓存功能,所以结构越简单越好,这里我们只需要准备一台nginx的虚拟机即可,如果没有nginx,那么我们可以使用epel源,yum安装一个即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#添加epel源
root@~>> wget -O /etc/yum.repos.d/epel.repohttp://mirrors.aliyun.com/repo/epel-6.repo
#yum安装nginx
root@~>> yum install nginx -y
#rpm -ql查看主要配置文件位置
root@~>> rpm -ql nginx
这里为了简单,只使用简单的nginx.conf配置文件:
root@nginx>> cat nginx.conf
user              nginx;
worker_processes  1;
error_log /var/log/nginx/error.log;
pid       /var/run/nginx.pid;
events {
   worker_connections  1024;
}
http {
   include      /etc/nginx/mime.types;
   default_type application/octet-stream;
   log_format  main  '$remote_addr - $remote_user [$time_local]"$request" '
                      '$status $body_bytes_sent"$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';
   sendfile        on;
   keepalive_timeout  65;
   server {
       listen 80;
       location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
       }
   }
}

启动查看初始界面是否正常:

1
2
3
4
5
6
7
8
9
10
11
12
root@nginx>> nginx
root@nginx>> netstat -tupln|grepnginx
tcp       0      0 0.0.0.0:80           0.0.0.0:*                   LISTEN      1043/nginx
root@nginx>> curl -I 192.168.16.199
HTTP/1.1 200 OK
Server: nginx/1.0.15
Date: Mon, 14 Sep 2015 09:40:53 GMT
Content-Type: text/html
Content-Length: 3698
Last-Modified: Tue, 16 Jun 2015 21:34:15GMT
Connection: keep-alive
Accept-Ranges: bytes

一切正常,首页有2张图片,正好用于实验:

1
2
3
4
5
6
7
root@html>> tree/usr/share/nginx/html/
/usr/share/nginx/html/
|-- 404.html
|-- 50x.html
|-- index.html
|-- nginx-logo.png
`-- poweredby.png

至此环境准备完毕。

2  配置cache

2.1  创建目录并挂载tmpfs

nginx的proxy_cache是基于内存和磁盘的缓存,需要指定缓存目录和临时目录:

root@nginx>> mkdir /tmp/{ngx_tmp,ngx_cache}-p

缓存存放于磁盘,磁盘IO会影响缓存的速度,所以我们在将tmpfs挂载于ngx_cache目录上来加速缓存的读取和写入:

1
2
3
4
root@nginx>> mount -t tmpfs -osize=100M tmpfs /tmp/ngx_cache
root@nginx>> mount|grep tmpfs
tmpfs on /dev/shm type tmpfs (rw)
tmpfs on /tmp/ngx_cache type tmpfs (rw,size=100M)

2.2  配置缓存目录大小以及key空间名

将下面配置放至http标签中:

root@nginx>> grep proxy_cache_pathnginx.conf

proxy_cache_path /tmp/ngx_cache levels=1:2 keys_zone=cache_one:100minactive=1d max_size=5g;

#指定缓存目录,缓存等级,键空间名,键空间大小,失效时间,以及磁盘最大缓存大小

2.3  配置反向代理

首先配置upstream节点池:

1
2
3
upstream server_pool {
   server 127.0.0.1:8080;
}

在server标签的location段中配置代理:

proxy_pass http://server_pool;

配置8080端口的标签:

1
2
3
4
5
6
7
8
server {
   listen 8080;
   location / {
       root /usr/share/nginx/html;
       index index.html index.htm;
   }
   access_log /var/log/nginx/access.log  main;
}

配置proxy_cache相关参数启用缓存:

1
2
3
4
5
6
7
8
9
10
proxy_pass http://server_pool;
proxy_next_upstream http_502 http_504error timeout invalid_header; #出错尝试下一个节点
proxy_cache cache_one;      #缓存键空间名
proxy_cache_valid 200 304 12h; #指定对应状态码的缓存时间
proxy_cache_valid 301 302 1m;
proxy_cache_valid any 1m;
proxy_cache_key $host$uri$is_args$args; #指定键key的格式
proxy_set_header Host $host;        #传递主机名给后端节点
proxy_set_header X-Forwarded-For$remote_addr; #传递客户端IP给后端节点
expires 1d; #超期时间

最终的nginx.conf配置文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
root@nginx>> cat nginx.conf
user              nginx;
worker_processes  1;
error_log /var/log/nginx/error.log;
pid       /var/run/nginx.pid;
events {
   worker_connections  1024;
}
http {
   include      /etc/nginx/mime.types;
   default_type application/octet-stream;
   log_format  main  '$remote_addr - $remote_user [$time_local]"$request" '
                      '$status $body_bytes_sent"$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"'
                                         '"addr:$upstream_addr-status:$upstream_status-cachestatus:$upstream_cache_status"';
   sendfile        on;
   keepalive_timeout  65;
       proxy_cache_path /tmp/ngx_cache levels=1:2 keys_zone=cache_one:100m inactive=1dmax_size=5g;
       upstream server_pool {
                server 127.0.0.1:8080;
       }
   server {
                listen 80;
       location / {
                        proxy_passhttp://server_pool;
                        proxy_next_upstreamhttp_502 http_504 error timeout invalid_header;
                        proxy_cache cache_one;
                        proxy_cache_valid 200304 12h;
                        proxy_cache_valid 301302 1m;
                        proxy_cache_valid any 1m;
                        proxy_cache_key$host$uri$is_args$args;
                        proxy_set_header Host$host;
                        proxy_set_headerX-Forwarded-For $remote_addr;
                        expires 1d;
       }
       access_log /var/log/nginx/cache_access.log main;
   }
       server {
                listen 8080;
                location / {
                        root/usr/share/nginx/html;
                        index index.htmlindex.htm;
                }
       }
}

2.4  配置日志

为了观察缓存的命中状态,我们可以将缓存相关的变量记录在日志中。

定义日志格式:

1
2
3
4
log_format main  '$remote_addr - $remote_user[$time_local] "$request" '
                  '$status $body_bytes_sent"$http_referer" '
                  '"$http_user_agent""$http_x_forwarded_for"'
                 '"addr:$upstream_addr-status:$upstream_status-cachestatus:$upstream_cache_status"';

#其中upstream_addr记录分发的后端节点IP;upstream_status记录后端节点返回的状态码;upstream_cache_status记录缓存的命中情况。

在反向代理标签中引用日志:

access_log /var/log/nginx/cache_access.log  main;

nginx重新加载配置:

root@nginx>> nginx -s reload

2.5  监测缓存

监测缓存文件的事件

浏览网站:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
root@ngx_cache>> inotifywait -mrq/tmp/ngx_cache/
/tmp/ngx_cache/ CREATE,ISDIR 6
/tmp/ngx_cache/ OPEN,ISDIR 6
/tmp/ngx_cache/ CLOSE_NOWRITE,CLOSE,ISDIR6
/tmp/ngx_cache/ CREATE,ISDIR 1
/tmp/ngx_cache/ OPEN,ISDIR 1
/tmp/ngx_cache/ CLOSE_NOWRITE,CLOSE,ISDIR1
/tmp/ngx_cache/ CREATE,ISDIR 3
/tmp/ngx_cache/ OPEN,ISDIR 3
/tmp/ngx_cache/ CLOSE_NOWRITE,CLOSE,ISDIR3
/tmp/ngx_cache/3/ CREATE,ISDIR fd
/tmp/ngx_cache/3/ OPEN,ISDIR fd
/tmp/ngx_cache/3/CLOSE_NOWRITE,CLOSE,ISDIR fd
/tmp/ngx_cache/3/fd/ CREATEdd404cd351f6b9efb072e5806dc2efd3.0000000026
/tmp/ngx_cache/3/fd/ OPENdd404cd351f6b9efb072e5806dc2efd3.0000000026
/tmp/ngx_cache/3/fd/ MODIFYdd404cd351f6b9efb072e5806dc2efd3.0000000026
/tmp/ngx_cache/3/fd/ CLOSE_WRITE,CLOSEdd404cd351f6b9efb072e5806dc2efd3.0000000026
/tmp/ngx_cache/3/fd/ MOVED_FROMdd404cd351f6b9efb072e5806dc2efd3.0000000026
/tmp/ngx_cache/3/fd/ MOVED_TOdd404cd351f6b9efb072e5806dc2efd3

说明:有最后几行可知,图片缓存到目录中。

提示:本内容来自老男孩教育运维23期、云计算与DevOps高级架构师课程13期学员笔记

更多内容请看老男孩教育的Linux课程 http://www.oldboyedu.com

本文出自 “老男孩linux培训” 博客,请务必保留此出处http://oldboy.blog.51cto.com/2561410/1884326

使用nginx cache缓存网站数据实践的更多相关文章

  1. 八.nginx网站服务实践应用

    期中集群架构-第八章-期中架构nginx章节====================================================================== 01. web ...

  2. Nginx 负载均衡的Cache缓存批量清理的操作记录

    1)nginx.conf配置 [root@inner-lb01 ~]# cat /data/nginx/conf/nginx.conf user www; worker_processes 8; #e ...

  3. 使用nginx lua实现网站统计中的数据收集

    导读网站数据统计分析工具是各网站站长和运营人员经常使用的一种工具,常用的有 谷歌分析.百度统计和腾讯分析等等.所有这些统计分析工具的第一步都是网站访问数据的收集.目前主流的数据收集方式基本都是基于ja ...

  4. 网站集群架构(LVS负载均衡、Nginx代理缓存、Nginx动静分离、Rsync+Inotify全网备份、Zabbix自动注册全网监控)--技术流ken

    前言 最近做了一个不大不小的项目,现就删繁就简单独拿出来web集群这一块写一篇博客.数据库集群请参考<MySQL集群架构篇:MHA+MySQL-PROXY+LVS实现MySQL集群架构高可用/高 ...

  5. Nginx content cache Nginx内容缓存

    原文地址:http://nginx.com/resources/admin-guide/caching/ Nginx content cache Nginx内容缓存 This chapter desc ...

  6. ASP.NET MVC5 网站开发实践(一) - 框架(续) 模型、数据存储、业务逻辑

    上次搭建好了项目框架,但还是觉得不太对劲,后来才想起来没有对开发目标进行定位,这个小demo虽然不用做需求分析,但是要实现什么效果还得明确.后来想了一下就做个最简单的网站,目标定为小公司进行展示用的网 ...

  7. Cache 应用程序数据缓存

    System.Web.Caching 命名空间提供用于缓存服务器上常用数据的类.此命名空间包括 Cache 类,该类是一个字典,您可以在其中存储任意数据对象,如哈希表和数据集.它还为这些对象提供了失效 ...

  8. nginx+redis缓存微信的token数据

    上一篇文章我们讲了如何在负载均衡的项目中使用redis来缓存session数据,戳这里. 我们在项目的进展过程中,不仅需要缓存session数据,有时候还需要缓存一些别的数据,比如说,微信的acces ...

  9. Nginx proxy开启cache缓存

    proxy_temp_path /tmp/proxy_temp_dir; // 设置缓存位置 proxy_cache_path /tmp/proxy_cache_dir levels = : keys ...

随机推荐

  1. Asp.Net生命周期和Http管道技术

    本篇主要介绍一下内容: 1.ASP.NET生命周期 2.Http运行时 3.Http管道技术 a)inetinfo.exe b)asp.net_isapi.dll c)aspnet_wp.exe d) ...

  2. SpringBoot项目设置热部署

    记录一个SpringBoot 设置热部署(修改项目之后,项目自动重启)实例 POM.XML 文件 <!-- 配置springBoot项目的热部署启动 --> <dependency& ...

  3. python socket timeout设置

    需要在调用socket的connect方法之前设置settimeout(time)方法,另外在设置之后要将再次调用settimeout(None)来设置socket进入阻塞模式. 如下代码示例: so ...

  4. iOS:使用集成的支付宝SDK的支付流程

    基本步骤: 1.先与支付宝签约,获得商户的ID(partner)和账号ID(seller),这一部分主要是又公司负责: 2.下载相应的公钥私钥文件,用来给签名进行加密: 3.下载支付宝集成的SDK,网 ...

  5. 深入理解AMD和RequireJS!

    AMD 基于commonJS规范的nodeJS出来以后,服务端的模块概念已经形成,很自然地,大家就想要客户端模块.而且最好两者能够兼容,一个模块不用修改,在服务器和浏览器都可以运行.但是,由于一个重大 ...

  6. 项目笔记:导出Excel功能

    1.前台这块: var ids=""; $.post("${basePath}/assets/unRegDeviceAction_getDeviceIds.do" ...

  7. 怎样在caffe中添加layer以及caffe中triplet loss layer的实现

    关于triplet loss的原理.目标函数和梯度推导在上一篇博客中已经讲过了.详细见:triplet loss原理以及梯度推导.这篇博文主要是讲caffe下实现triplet loss.编程菜鸟.假 ...

  8. Hadoop之Storm基础

    1.离线计算是什么 离线计算:批量获取数据,批量传输数据,周期性批量计算数据,数据展示 代表技术:sqoop批量导入数据,hdfs批量存储数据,mapreduce批量计算数据,hive批量计算数据,* ...

  9. FIS 配置小诀窍

    之前用 FIS 的时候,发现配置 roadmap 的时候出现了非常诡异的现象:命令行使用 -o 参数,配置文件里对 html 不使用优化,导致 uglify 了 js 文件后,不会修改 html 中对 ...

  10. bootstrap popover 如何在hover状态移动到弹出上不消失

    bootstrap中的popover其实就是对tooltip做了一定升级,拥有了标题和内容 概要 使用的时候依赖第三方插件 依赖tooltip插件 必须初始化 title 和 content 可以在p ...