CDN实现varnish缓存

实验环境:

server5:varnish机(ip:172.25.254.5)
server2:real server机(ip:172.25.254.2)
server3:real server机(ip:172.25.254.3)

server5配置

一、安装varnish相关软件

[root@server5 ~]# yum install -y varnish-libs-3.0.5-1.el6.x86_64.rpm 
[root@server5 ~]# yum install -y varnish-3.0.5-1.el6.x86_64.rpm 

二、修改varnish配置文件

vim /etc/sysconfig/varnish 

修改varnish的端口

未分类

vim /etc/varnish/default.vcl

backend default {
  .host = "172.25.20.2";
  .port = "80";
}

三、修改内核显示,保证流量大时,服务正常运行

[root@server5 ~]# vim /etc/security/limits.conf 

未分类

四、varnish主机配置

修改varnish配置文件

backend web1 {   ##访问web1时,指向172.25.20.2
  .host = "172.25.254.2";
  .port = "80";
}

backend web2 {   ##访问web1时,指向172.25.20.3
  .host = "172.25.254.3";
  .port = "80";
}

sub vcl_recv {   ##www.westos.org和westos.org指向同一地址,节省varnish空间
         ##实质上,域名不同,varnish缓存地址不同
if (req.http.host ~ "^(www.)?westos.org") {
set req.http.host = "www.westos.org";
set req.backend = web1;
} elsif (req.http.host ~ "^bbs.westos.org") {
set req.backend = web2;
} else {error 404 "westos cache";
}
}

sub vcl_deliver {   ##第一次访问时MISS,后续访问HIT,varnish默认清楚时间120s
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT from westos cache";
}
else {
set resp.http.X-Cache = "MISS from westos cache";
}
return (deliver);
}

测试:
在物理机做域名解析:

172.25.254.5    www.westos.org  bbs.westos.org  westos.org

未分类

未分类

五、varnish负载均衡设置

server5

1、修改配置文件

backend web1 {
  .host = "172.25.254.2";
  .port = "80";
}

backend web2 {
  .host = "172.25.254.3";
  .port = "80";
}
director lb round-robin {     ##轮询操作
{ .backend = web1; }
{ .backend = web2; }
}
sub vcl_recv {
if (req.http.host ~ "^(www.)?westos.org") {
set req.http.host = "www.westos.org";
set req.backend = lb;       ##调用轮询
return (pass);
} elsif (req.http.host ~ "^bbs.westos.org") {
set req.backend = web2;      ##直接访问,不参与轮询
} else {error 404 "westos cache";   
}
}

server3开启httpd虚拟主机设置

/etc/httpd/cong/httpd.conf

未分类

重新启动server3的httpd服务

测试:

物理机访问:

未分类

六、varnish推送管理

目的:当web有更新时,varish的cache实现同步更新
安装httpd,php,unzip
修改httpd端口8080
默认发布目录/var/www/html下解压 bansys.zip
修改varnish配置文件 /etc/varnish/default.vcl
acl westos {
"127.0.0.1";
"172.25.254.0"/24;   指定 254 网段的可以推送
}

backend web1 {
.host = "172.25.254.2";   指定服务器
.port = "80";
}

backend web2 {
.host = "172.25.254.3";   指定服务器
.port = "80";
}
director lb round-robin {       轮巡
{       .backend = web1;        }
{       .backend = web2;        }
}
sub vcl_recv {

if (req.request == "BAN") {     如果输入错误  则 报错
if (!client.ip ~ westos) {
error 405 "Not allowed.";
}
ban("req.url ~ " + req.url);
error 200 "ban added";
}

if (req.http.host ~ "^(www.)?westos.org") {
set req.http.host = "www.westos.org";
set req.backend = lb;    引用 lb 函数  参加轮训
} elsif (req.http.host ~ "^bbs.westos.org") {
set req.backend = web2;
} else {error 404 "westos cache";
}
}
sub vcl_deliver {
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT from westos cache";
}                 命中缓存
else {
set resp.http.X-Cache = "MISS from westos cache";
}      未命中缓存
return (deliver);
}

访问 172.25.254.5:8080 即可进行推送
varnishadm ban.url /index.html
清除 index.html 页面缓存
varnishadm ban.url /admin/$
清除 admin 目录缓存

nginx+varnish+angular universal实现服务端页面渲染缓存

项目使用angular universal实现服务端渲染,为了减轻服务器的压力,需要将用户频繁访问的页面进行缓存,这样就不必每次都去渲染相同的页面(例如首页),angular universal在features中有提到考虑加入缓存,但就目前来说,varnish是个不错的选择,但是varnish不支持https,所以还需要用nginx进行端口的转发

总的思路

  1. nginx监听80端口将http重定向到https
  2. nginx监听443端口,并将443端口的请求转发到8080端口
  3. varnish监听8080端口的请求,如果与缓存中的页面匹配,则返回页面,如果没有匹配的页面,则请求pm2启动的服务

总的流程

  1. 安装与配置nginx
  2. 安装SSL证书,nginx配置SSL
  3. 安装与启动PM2
  4. 安装与配置varnish

Nginx的安装与配置

1、安装nginx

yum install nginx

2、配置nginx以安装SSL证书 ( 使用varnish时,不需要nginx监听80端口,nginx监听443端口然后转发到80端口即可 )

//找到nginx配置文件所在目录
Linux code: nginx -t

//打开nginx.conf文件配置一个server
server {
    listen       80;  //监听的端口
    server_name  yourdiamond.com; //域名
    root         /usr/local/web/Panoramic; //文件路径
    location / {
        index  index.html; //主页
    }
}

//检查配置是否有误
Linux code: nginx -t

3、开启gzip

//在config文件中加入以下代码
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_comp_level 5;
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php;

4、启动nginx

service nginx start/restart/reload(修改配置后无需重启,reload即可)/stop

Certbot证书配置

1、下载certbot

//安装git
yum install git

git clone https://github.com/certbot/certbot
cd certbot

2、安装证书

./certbot-auto certonly --webroot --agree-tos -v -t --email 邮箱地址 -w 网站根目录 -d 网站域名

//安装成功后会看到这样的信息,在配置nginx时会用上
Congratulations! Your certificate and chain have been saved at:
   /etc/******/fullchain.pem
   Your key file has been saved at:
   /etc/******/privkey.pem
   Your cert will expire on 2018-06-28. To obtain a new or tweaked
   version of this certificate in the future, simply run certbot-auto
   again. To non-interactively renew *all* of your certificates, run
   "certbot-auto renew"

3、证书的有效期为3个月,需要更新证书

./certbot-auto renew

Nginx配置SSL

1、在nginx.conf文件中,新加一个server,将443端口转发到8080端口

server {
    listen 443 ssl;
    server_name yourdiamond.com;
    //将ssl证书生成后的pem路径复制到ssl_certificate、ssl_certificate_key
    ssl_certificate /etc/******/fullchain.pem;
    ssl_certificate_key /etc/******/privkey.pem;
    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-Port 443;
        proxy_set_header Host $host;
    }
}

PM2

1、安装pm2

npm install pm2 -g

2、启动pm2

//启动参数
--watch 监视项目,如有更改自动重启
-n 为项目命名

pm2 start /usr/local/web/PCbeta/server.js --watch -n PC_SSR_beta

3、pm2命令

pm2 list  //列出所有应用
pm2 stop all  //停止所有应用
pm2 stop name|app_id  //停止指定的应用
pm2 restart name|app_id  //重启指定的应用
pm2 logs  //查看日志

4、对于angular universal应用,需要将生成的dist目录、dist-server目录、server.js一并复制到项目文件夹中

Varnish

1、修改varnish配置

//找到varnish所在目录
Linux code: whereis varnish

//打开 varnish.params,修改varnish监听的端口为8080,接收该端口的http请求
VARNISH_LISTEN_PORT=8080

//打开 default.vcl
//修改指向服务器的地址和端口(pm2运行的端口)
backend pc {
    .host = "127.0.0.1"; //指向本地服务器
    .port = "4000";  //监听4000端口运行的程序
}

//可同时存在多个backend,实现多域名同时使用varnish缓存
backend pcbeta {
    .host = "127.0.0.1"; 
    .port = "4001";  
}
//对不需要使用cookie的页面屏蔽cookie检查,提高命中率,cookie不同varnish会认为是不同的页面,这里只对包含home路径的页面进行检查

sub vcl_recv{
    if (!(req.url ~ "^/home/")) {
        unset req.http.Cookie;
    }
}

2、varnish命令,中文文档https://jefferywang.gitbooks.io/varnish_4_1_doc_zh/content/

//启动
service varnish start

//停止
service varnish stop

//查看统计日志

varnishtop:读取共享内存中的日志,同时会显示一个不断更新的列表

varnishhist:读取varnishd共享内存日志,同时生成一个连续不断更新的柱状图显示最后 N 个请求的分布。

N的值和垂直比例尺显示在左上角的位置。水平刻度是对数的,命中标记是“|”,未命中标记是“#”。

varnishstat:统计未命中、命中、存储信息、线程创建、删除对象等

OpenResty + Varnish Cache 实现 WP 的高性能加载教程

前言

Varnish Cache 是一款高性能的开源HTTP加速器,挪威最大的在线报纸 Verdens Gang 使用3台 Varnish 代替了原来的 12 台 Squid,性能比以前更好。(超级老的梗了,但是就这么用吧。)

Varnish Cache 在高端 WordPress 托管上也是非常常见的,由其构成的 Web 服务缓存加速解决方案已经非常成熟了,不过由于其开发者在 HTTPS 问题上并不关切所以很多人又抛弃了它采用了其他方案,不过前面也有提到 Varnish Cache 成熟、稳定,所以尽管不支持 HTTPS,我们也可以再加一层 Nginx 来反代实现 HTTPS。

介绍

Varnish Cache 的开发公司 Varnish Software 从 V5 时代开始了全新的命名方式,我们常提到的 Varnish 由 Varnish-Cache 的命名方式代替。

常见的 Varnish Cache 缓存规则从 V4 开始已经不同于 V3 了,不过 V5 依旧向下兼容 V4 的规则。

本教程主要介绍和前面的 https://www.mf8.biz/the-guide-for-wordpress-ubuntu/ 相呼应。

具体的教程可以参考:https://www.mf8.biz/varnish-wordpress-make-fast-1/

安装 Varnish 5

curl -s https://packagecloud.io/install/repositories/varnishcache/varnish5/script.deb.sh | bash
apt-get install varnish

更多系统的安装请看:

https://www.varnish-cache.org/releases/index.html https://packagecloud.io/varnishcache/varnish5/install

设置 Nginx

编辑虚拟主机的配置文件,将之前的 80 端口内容改成 8080 端口,其实就是将 listen 后改成 8080 ,例如:

  server {
  ##运行端口
  listen 8080; 

  ##这里需要改成你的域名
  server_name www.mf8.biz; 

  access_log /data/wwwlogs/access_nginx.log combined; #日志目录
  root /data/wwwroot/build; #网站文件目录
  index index.html index.htm index.php; #首页文件优先级
  include /usr/local/openresty/nginx/conf/rewrite/wordpress.conf;

  ##PHP
  location ~ [^/].php(/|$) {
      fastcgi_pass unix:/run/php/php7.1-fpm.sock;
      fastcgi_index index.php;
      include fastcgi.conf;
      fastcgi_param PHP_VALUE "open_basedir=$document_root:/tmp/:/proc/";
    }

  ##下面的都是缓存
  location ~ .*.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
    expires 30d;
    access_log off;
    }
  location ~ .*.(js|css)?$ {
    expires 7d;
    access_log off;
    }
  location ~ /.ht {
    deny all;
    }
  }

同理,/usr/local/openresty/nginx/conf/nginx.conf 文件也必须将之前的 80 端口改成 8080 端口,其他所有在 Nginx 上打开的 80 端口都需要修改,不然 Varnish 无法启动。

然后将 HTTPS 部分,改成反代:

    server {

  ##开启 HTTPS 和 HTTP/2
  listen 443 ssl http2;

  ssl_certificate /usr/local/openresty/nginx/conf/ssl/www.mf8.biz.crt; #RSA证书
  ssl_certificate_key /usr/local/openresty/nginx/conf/ssl/www.mf8.biz.key; #RSA密钥

  ##SSL增强安全设置部分
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+ECDSA+AES128:EECDH+aRSA+AES128:RSA+AES128:EECDH+ECDSA+AES256:EECDH+aRSA+AES256:RSA+AES256:EECDH+ECDSA+3DES:EECDH+aRSA+3DES:RSA+3DES:!MD5;
  ssl_prefer_server_ciphers on;
  ssl_session_timeout 10m;
  ssl_session_cache builtin:1000 shared:SSL:10m;
  ssl_buffer_size 1400;
  ssl_stapling on;
  ssl_stapling_verify on;

  server_name www.mf8.biz;
  access_log off;

        location / {
            proxy_pass http://127.0.0.1:80;
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto https;
            proxy_set_header X-Forwarded-Port 443;
            proxy_set_header Host $host;
        }
}

设置 Varnish

cd /etc/varnish/
mv default.vcl default.vclold
git clone https://gitee.com/mf8/varnish-caching-wordpress.git

cd /lib/systemd/system/
mv varnish.service varnish.service.old
wget https://gitee.com/yunvy/codes/d79nhgw2aitm8xky65p4399/raw?blob_name=varnish.service

cd /etc/default
mv varnish varnish.old
wget https://gitee.com/yunvy/codes/folh28bm9ipveagc04ws740/raw?blob_name=varnish

systemctl daemon-reload
service varnish restart

设置 WordPress

不过呢,由于我们是 Nginx HTTPS 443 端口 —— Varnish 80 端口 —— Nginx 80 端口 饶了三层,所以 WP 就会反应不过来,所有的静态资源的加载依旧走的 HTTP ,这里就需要额外设置一下了。

修改 wp-config.php 文件,加入:

if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')  $_SERVER['HTTPS']='on';

因为我们在 Nginx 443 反代的时候加入了 proxy_set_header X-Forwarded-Proto https; ,所以当 WP 检测 HTTP_X_FORWARDED_PROTO 有 https 反馈的时候就会将静态资源的加载自动走 HTTPS 了!

Varnish后端主机的健康状态检查

配置后端主机的Health Check

环境

Varnish      192.168.198.139
图片服务端    192.168.198.120
程序服务端    192.168.198.128

程序服务器

[root@danran ~]# vim /var/www/html/.healthchk.html
ok

图片服务器

[root@centos6 ~]# vim /data/web/image2/.healthchk.html
oK
[root@centos6 ~]# vim /data/web/images/.healthchk.html
ok

Vernish

[root@danran ~]# vim /etc/varnish/default.vcl
    导入directors模块
    import directors;

    定义健康检查的机制,自定义为healthchk
    probe healthchk {
        .url = "/.healthchk.html";\检查的url为.healthchk.html
        .timeout = 2s;  \超时时间为2s
        .interval = 2s;\检查间隔时间
        .window = 8; \基于最近8次的检查判断
        .threshold = 5; \检查最近8次若有5次成功即为健康状态
    }

    定义一个app程序后端服务器
    backend appsrv1 {
        .host = "192.168.198.128";
        .port = "80";
        .probe = healthchk; \调用健康检查的机制
    }

    定义两个图片服务端
    backend imgsrv1 {
        .host = "192.168.198.120";
        .port = "80";
        .probe = healthchk; \调用健康检查的机制
    }
    backend imgsrv2 {
        .host = "192.168.198.120";
        .port = "8080";
        .probe = healthchk; \调用健康检查的机制
    }

    定义一个图片服务器组imgsrvs,并将imgsrv1和imgsrv2两个后端图片服务器添加进imgsrvs组中
    sub vcl_init {
        new imgsrvs =  directors.round_robin();  \指定调度算法为轮询
        imgsrvs.add_backend(imgsrv1);
        imgsrvs.add_backend(imgsrv2);
    }

    sub vcl_recv {
        if (req.url ~ "(?i).(jpg|jpeg|png|gif|svg|txt)$") {
            set req.backend_hint = imgsrvs.backend();
        } else {
            set req.backend_hint = appsrv1;
        }
    }
[root@danran ~]# varnish_reload_vcl    \重新加载/etc/varnish/default.vcl参数文件

Varnish查看后端主机的健康状态

[root@danran ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082 
backend.list
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8 \Healthy为健康状态,检测了8次,8次成功
imgsrv1(192.168.198.120,,80)   7      probe      Healthy 8/8
imgsrv2(192.168.198.120,,8080) 6      probe      Healthy 8/8

图片服务端故障了一台服务器

添加一条防火墙规则,禁止8080端口的连接,即等同于imgsrv2服务器的故障
[root@centos6 ~]# iptables -A INPUT -p tcp --dport 8080 -j REJECT  

Varnish查看后端主机的健康状态

[root@danran ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082 
backend.list
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      probe      Healthy 8/8
imgsrv2(192.168.198.120,,8080) 6      probe      Sick 0/8  \检查80次,0次成功,即imgsrv2服务端故障,从而imgsrv2不可用

修复使imgsrv2上线后,imgsrv2恢复正常状态 
[root@danran ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082 
backend.list
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      probe      Healthy 8/8
imgsrv2(192.168.198.120,,8080) 6      probe      Sick 4/8  \Sick为失败状态
backend.list
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      probe      Healthy 8/8
imgsrv2(192.168.198.120,,8080) 6      probe      Healthy 5/8 \当检查次数大于等于5次时,即表示该服务端可以正常使用

Varnish手动使某后台服务端下线,即修改服务器健康状态为sick

[root@Varnish ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082
backend.set_health imgsrv1 sick
200 \将imgsrv1服务器的状态手动修改为sick故障状态      

backend.set_healtlist
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      sick       Healthy 8/8 \imgsrv1状态为sick故障状态
imgsrv2(192.168.198.120,,8080) 6      probe      Healthy 8/8

将手动修改为sick状态的后台服务器端上线,即将状态修改为health

[root@Varnish ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082

backend.set_health imgsrv1 healthy
200 \将imgsrv1服务器的状态手动修改为healthy健康状态,即不管物理后台服务器端是否正常,varnish检测结果都为正常

backend.set_healtlist
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      sick       Healthy 8/8 \imgsrv1状态为sick故障状态
imgsrv2(192.168.198.120,,8080) 6      probe      Healthy 8/8

backend.set_healtlist
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      healthy    Healthy 8/8
imgsrv2(192.168.198.120,,8080) 6      probe      Healthy 8/8
imgsrv1后台服务器端故障,不能正常使用

[root@imgsrv1 ~]# iptables -A INPUT -p tcp --dport 80 -j REJECT 

Varnish检测后端服务器的健康状态

[root@Varnish ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082

backend.list
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      healthy    Sick 0/8
imgsrv2(192.168.198.120,,8080) 6      probe      Healthy 8/8

将手动修改为sick状态的后台服务器端上线,即将状态修改为health

[root@Varnish ~]# varnishadm -S /etc/varnish/secret -T

backend.set_healtlist
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      sick       Healthy 8/8 \imgsrv1状态为sick故障状态
imgsrv2(192.168.198.120,,8080) 6      probe      Healthy 8/8

backend.set_health imgsrv1 auto
200        

backend.set_healtlist
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      probe      Healthy 8/8
imgsrv2(192.168.198.120,,8080) 6      probe      Healthy 8/8  

imgsrv1后台服务器端故障,不能正常使用

[root@imgsrv1 ~]# iptables -A INPUT -p tcp --dport 80 -j REJECT 

Varnish检测后端服务器的健康状态

[root@Varnish ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082

backend.set_healtlist
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      probe      Sick 0/8
imgsrv2(192.168.198.120,,8080) 6      probe      Healthy 8/8

修复imgsrv1,使imgsrv1上线1

[root@Varnish ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082

backend.set_healtlist
200        
Backend name                   Refs   Admin      Probe
appsrv1(192.168.198.128,,80)   7      probe      Healthy 8/8
imgsrv1(192.168.198.120,,80)   7      probe      Healthy 8/8
imgsrv2(192.168.198.120,,8080) 6      probe      Healthy 8/8

Varnish配置示例说明

Varnish与一般服务器软件类似,分为master(management)进程和child(worker,主要做cache的工作)进程。master进程读入命令,进行一些初始化,然后fork并监控child进程。child进程分配若干线程进行工作,主要包括一些管理线程和很多woker线程。

varnish架构图:

未分类

varnish的配置示例:

1、主配置文件的修改:

varnish作为web服务的反向代理服务器,要监听在80端口,因此要修改配置文件:

vim /etc/varnish/varnish.params

未分类

记得创建你所指定的路径:mkdir /data/varnish/cache

并将属主属组修改为varnish:chown -R varnish:varnish /data/varnish/cache

2、配置后端主机:

vim /etc/varnish/default.vcl

未分类

后端主机安装httpd作为测试

重读default.vcl文件:varnsih_reload_vcl 或者通过交互式方式重载配置varnish配置:varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082

命令行下:

vcl.load <configname> <filename> 重载配置文件default.vcl(filename),并将其命名
vcl.use <configname>使用新生成的配置

网页通过http访问此varnish主机得到:

未分类

说明后端主机配置成功

3、VCL: ”域“专有类型的配置语言

VCL有多个状态引擎,状态之间存在相关性,但状态引擎彼此间互相隔离;每个状态引擎可使用return(x)指明关联至哪个下一级引擎;每个状态引擎对应于vcl文件中的一个配置段,即为subroutine

变量类型:

内建变量:

  • req.*:request,表示由客户端发来的请求报文相关;
  • bereq.*:由varnish发往BE主机的httpd请求相关;
  • resp.*:由varnish响应给client相关;
  • obj.*:存储在缓存空间中的缓存对象的属性;只读;

常用变量:

  • bereq.*, req.*:
  • bereq.http.HEADERS
  • bereq.request:请求方法;
  • bereq.url:请求的url;
  • bereq.proto:请求的协议版本;
  • bereq.backend:指明要调用的后端主机;
  • req.http.Cookie:客户端的请求报文中Cookie首部的值;
  • req.http.User-Agent ~ “chrome”
  • beresp.*, resp.*:
  • beresp.http.HEADERS
  • beresp.status:响应的状态码;
  • reresp.proto:协议版本;
  • beresp.backend.name:BE主机的主机名;
  • beresp.ttl:BE主机响应的内容的余下的可缓存时长;
  • obj.*
  • obj.hits:此对象从缓存中命中的次数 >1 表示命中;
  • obj.ttl:对象的ttl值
  • server.*
  • server.ip
  • server.hostname
  • client.*
  • client.ip

介绍几个VCL配置的实例:

(1)添加报文首部:vim default.vcl

obj.hits是内建变量,用于保存某缓存项的从缓存中命中的次数;

在sub vcl_deliver中添加

if (obj.hits>0) {

          set resp.http.X-Cache = “HIT via ” + server.ip;
   } else {
          set resp.http.X-Cache = “MISS via ” + server.ip;
   }

在交互式命令行下手动装载配置,并使用:

vcl.load  test default.vcl

vcl_use test

测试:

未分类

刷新网页,再次访问,会出现“HIT via….”字样

(2)强制对某类资源的请求不检查缓存,在请求报文中包含以/login|admin 为首的不查缓存,直接送到backend(后端服务器):

sub   vcl_recv {
       if (req.url ~ “(?i)^/(login|admin)”) {
          return(pass);
       }
    }

禁止以curl方式访问:

sub   vcl_recv {
       if (req.http.User-Agent ~ “(?i)^/curl”) {
          return(synth(403));
       }
    }

测试:

未分类

(3)对于特定类型的资源,例如公开的图片等,取消其私有标识(cookie),并强行设定其可以由varnish缓存的时长;

sub  vcl_backend_response {

     if (beresp.http.cache-control !~ “s-maxage”) {
        if (bereq.url ~ “(?i).(jpg|jpeg|png|gif|css|js)$”) {
           unset beresp.http.Set-Cookie;
           set beresp.ttl = 3600s;
        }
      }

}

(4)设置后端服务器日志中记录真实的客户端地址:

sub vcl_recv {
    if (req.restarts == 0) {
       if (req.http.X-Fowarded-For) {
          set req.http.X-Forwarded-For = req.http.X-Forwarded-For + “,” + client.ip;
    } else {
         set req.http.X-Forwarded-For = client.ip;
       }
    }

}

并在后端服务器中设置日志格式:

vim  /etc/httpd/conf/httpd.conf

  将格式修改为:LogFormat  “%{X-Forwarded-For}i  %l  %u  %t  ”%r“ %>s %b  ” %{Referer}i” ”%{User-Agent}i”” combined

测试:

未分类

(5)访问控制

缓存对象的修剪:purge, ban

未分类

测试:缓存后,用curl查看网页信息

未分类

裁剪,将缓存删除:curl -X PURGE http://172.16.252.187/index.html

未分类

Banning 在交互式模式 用于临时按需要清理缓存

示例:

未分类

在配置文件中,使用ban()函数,相当于purge的用法;示例:

if (req.method == “BAN”) {
      ban(“req.http.host == ” + req.http.host + ” && req.url == ” + req.url);
      return(synth(200, “Ban added”));
}

清空一个域的缓存:

ban req.url == / && req.http.host ~ “ilinux.io”(慎用)

(6)负载均衡,Director:

使用前需要导入:import directors

示例:

未分类

未分类

动静分离配置示例:

         import directors

        …..
        backend imgsrv1 {
                .host = “192.168.251.11”;
                .port = “80”;
        }
        backend imgsrv2 {
                .host = “192.168.251.12”;
                .port = “80”;
        }
        backend appsrv1 {
                .host = “192.168.251.13”;
                .port = “80”;
        }
        backend appsrv2 {
                .host = “192.168.251.14”;
                .port = “80”;
        }
    sub vcl_init {
                new imgsrvs = directors.random();
                imgsrvs.add_backend(imgsrv1,10);
                imgsrvs.add_backend(imgsrv2,20);
                new staticsrvs = directors.round_robin();
                appsrvs.add_backend(appsrv1);
                appsrvs.add_backend(appsrv2);
                new appsrvs = directors.hash();
                appsrvs.add_backend(appsrv1,1);
                appsrvs.add_backend(appsrv2,1);
        }
     sub vcl_recv {
                  if (req.url ~ “(?i).(css|js)$” {
                        set req.backend_hint = staticsrvs.backend();
                }
                if (req.url ~ “(?i).(jpg|jpeg|png|gif)$” {
                       set req.backend_hint = imgsrvs.backend();
                } else {
                        set req.backend_hint = appsrvs.backend(req.http.cookie);
                }
      } 

(7)基于cookie的session sticky:

sub vcl_init {
       new h = directors.hash();
       h.add_backend(one, 1); // backend ‘one’ with weight ‘1’
       h.add_backend(two, 1); // backend ‘two’ with weight ‘1’
}
sub vcl_recv {
       set req.backend_hint = h.backend(req.http.cookie);
} 

(8)健康状态检测:

.probe:定义健康状态检测方法;
.url:检测时要请求的URL,默认为”/”;
.request:发出的具体请求;
    .request =
          “GET /.healthtest.html HTTP/1.1”
          “Host: www.magedu.com”
          “Connection: close”
    .window:基于最近的多少次检查来判断其健康状态;
    .threshold:最近.window中定义的这么次检查中至有.threshhold定义的次数是成功的;
    .interval:检测频度;
    .timeout:超时时长;
    .expected_response:期望的响应码,默认为200;

配置示例:

未分类

显示健康状态信息,在交互式界面中:

未分类

4、性能调整:vim /etc/varnish/varnish.params

根据对网页的测试来适当调整数值

未分类

5、varnish日志

1>、varnishstat – Varnish Cache statistics 各种计数器
         -1 批次显示,只显示1次
         -1 -f FILED_NAME
         -l:可用于-f选项指定的字段名称列表;
# varnishstat -1 -f MAIN.cache_hit -f MAIN.cache_miss
# varnishstat -l -f MAIN -f MEMPOOL
2>、varnishtop – Varnish log entry ranking 将日志文件中相关数据逆序排序
              -1 Instead of a continously updated display, print the statistics once and exit.
              -i taglist,可以同时使用多个-i选项,也可以一个选项跟上多个标签;筛选
              -I <[taglist:]regex>
              -x taglist:排除列表
              -X <[taglist:]regex>
varnishtop -i RespStatus 查看响应码
3>、varnishlog – Display Varnish logs 查看实时日志
4>、 varnishncsa – Display Varnish logs in Apache / NCSA combined log format 标准日志格式 

Ubuntu 16.04安装Magento 2 Varnish和Apache

Magento是一个免费的开源内容管理系统,内置PHP,Zend框架和MySQL数据库。 它是非常受欢迎的电子商务网络应用程序,运行在诸如Apache,MySQL等许多开源应用程序之上。 Magento配有大量内置模块,用于添加更多功能。

Varnish Cache是​​一个功能强大的开源Web应用程序加速器,也称为缓存HTTP反向代理。 它用于通过在用户第一次访问时缓存网页的副本来加快您的网站。 Magento和Varnish是一种已知的组合,可以显着提高现场性能。 默认情况下,Magento 2集成了Varnish。您只需要进行一些配置更改,使其正常工作。

在本教程中,我们将学习如何在Ubuntu 16.04服务器上将Magento 2与Varnish安装为全页缓存。

要求

  • 运行Ubuntu 16.04的服务器。
  • Apache,PHP和MariaDB。
  • 在您的服务器上设置sudo权限的非root用户。

1. 入门指南

在启动之前,建议使用最新的软件包通过运行以下命令来更新系统:

sudo apt-get update -y
sudo apt-get upgrade -y

一旦您的系统是最新的,请重新启动系统并使用sudo用户登录。

2. 安装LAMP服务器

Magento将无法安装LAMP(Apache,PHP,MariaDB)。 首先,通过运行以下命令安装Apache Web服务器和Varnish:

sudo apt-get install apache2 varnish -y

安装Apache后,启动Apache服务,并通过运行以下命令使其启动:

sudo systemctl start apache2
sudo systemctl enable apache2

Magento是用PHP语言编写的,所以您还需要将PHP与所有库一起安装到系统中。 您可以通过运行以下命令来安装它们:

sudo apt-get install php7.0 libapache2-mod-php7.0 php7.0-mbstring php7.0-mysql php7.0-mcrypt php7.0-xsl php-imagick php7.0-gd php7.0-cli php-pear php7.0-intl php7.0-curl php7.0-zip php7.0-gd php7.0-soap php7.0-xml -y

安装PHP以及所有必需的库后,您将需要更改几个默认的PHP设置。 您可以通过编辑php.ini文件来执行此操作:

sudo nano /etc/php/7.0/cli/php.ini

更改以下行:

memory_limit = 512
upload_max_filesize = 128M
zlib.output_compression = on
max_execution_time = 15000

完成后保存并关闭文件。

3. 安装并配置MariaDB

Magento使用MariaDB作为数据库。 所以你需要将它安装到你的服务器上。 您可以通过运行以下命令来安装它:

sudo apt-get install mariadb-server -y

安装MariaDB后,启动MariaDB服务,并通过运行以下命令使其在启动时启动:

sudo systemctl start mysql
sudo systemctl enable mysql

默认情况下,MariaDB不受保护,因此您需要确保它。 您可以通过运行以下命令来保护它:

sudo mysql_secure_installation

回答以下所有问题:

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

You already have a root password set, so you can safely answer 'n'.

Change the root password? [Y/n] n

 ... skipping.

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] Y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] Y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] Y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] Y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

接下来,使用以下命令登录到MariaDB shell:

mysql -u root -p

在提示时输入root密码,然后使用以下命令为Magento创建一个数据库:

MariaDB [(none)]>CREATE DATABASE magento_db;

为Magento创建数据库后,使用以下命令创建用户名和密码:

MariaDB [(none)]>CREATE USER ‘magento’@’localhost’ IDENTIFIED BY ‘password’;

接下来,使用以下命令将权限授予Magento数据库:

MariaDB [(none)]>GRANT ALL PRIVILEGES ON magento_db.* TO ‘magento’@’localhost’;

接下来,运行FLUSH PRIVILEGES命令,以退出特权:

MariaDB [(none)]>FLUSH PRIVILEGES;

最后,使用以下命令退出MariaDB控制台:

MariaDB [(none)]>q

4. 下载Magento

首先,您需要从官方网站下载最新版本的Magento。

下载Magento后,使用以下命令将下载的zip文件解压缩到apache web根目录:

sudo mkdir /var/www/html/magento/
sudo unzip magento2-develop.zip -d /var/www/html/magento

接下来,更改magento目录的所有权,并给予适当的许可:

sudo chown -R www-data:www-data /var/www/html/magento
sudo chmod -R 777 /var/www/html/magento

接下来,您需要将Composer安装到系统中。 Composer是一个依赖管理器,用于安装所有必需的PHP依赖关系。 您可以使用以下命令下载并安装Composer二进制文件:

curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/bin/composer

接下来,运行composer命令来安装Magento所需的所有依赖项:

cd /var/www/html/magento
sudo composer install

一旦安装了所有依赖项,您可以继续为Magento配置Apache。

5. 为Magento配置Apache

接下来,您需要为Magento创建Apache虚拟主机文件。 使用以下命令创建一个名为magento.conf的新Apache配置文件:

sudo nano /etc/apache2/sites-available/magento.conf

添加以下行:

<VirtualHost *:8080>
ServerAdmin [email protected]
DocumentRoot /var/www/html/magento
ServerName 192.168.15.189
ServerAlias www.example.com
<<Directory "/var/www/html/magento/">
Options FollowSymLinks
AllowOverride All
Order allow,deny
allow from all
</Directory>
ErrorLog /var/log/apache2/magento-error_log
CustomLog /var/log/apache2/magento-access_log common
</VirtualHost>

保存文件,然后使用Apache重写模块启用虚拟主机以下命令:

sudo a2ensite magento
sudo a2enmod rewrite

接下来,您还需要将Apache监听端口从80更改为8080.因为我们将为Varnish预留端口80。 要这样做,打开ports.conf文件:

sudo nano /etc/apache2/ports.conf

更改文件如下所示:

Listen 8080

最后,重新启动Apache服务以使用以下命令应用此更改:

sudo systemctl restart apache2

6. 访问Magento Web安装向导

Magento现已安装,现在是通过网络浏览器安装Magento的时候了。

要这样做,打开你的网页浏览器并输入URL http://192.168.15.189:8080 ,你应该看到以下页面:

Apache

现在,同意条款和条件,然后点击“同意和设置Magento”按钮,您应该看到以下页面:

Apache

检查所有准备状态,然后单击“下一步”按钮,您应该看到以下页面:

Apache

提供您的数据库详细信息,如数据库名称,数据库用户名和密码,然后单击“下一步”按钮,您应该看到以下页面:

Apache

提供您的网站详细信息,并点击“下一步”按钮,您应该看到以下页面:

Apache

根据您的需要定制Magento,然后点击“下一步”按钮,您将看到以下页面:

Apache

提供您的管理员用户详细信息,然后单击“下一步”按钮,您应该看到以下页面:

Apache

现在,点击“立即安装”按钮开始安装Magento。 安装完成后,您将看到以下页面:

Apache

注意:记住您的Magento管理员URL: http : //192.168.15.189/admin_wczta4 。 这将用于访问Magento管理员。

现在,点击“启动Magento管理”按钮,你应该看到Magento登录页面如下:

Apache

提供您的Magento管理员凭据并点击“登录”按钮,您应该看到Magent-o仪表板如下所示:

Apache

从您的Magento管理仪表板单击STORES按钮(左侧)>配置> ADVANCED>系统>全页缓存 ,然后取消选择使用系统值,并从缓存应用程序列表中选择Varnish缓存,保存配置,单击Varnish配置链接和单击导出VCL for Varnish 4按钮(这将导出var / www / html / magento / var directoy中的varnish.vcl文件),如下所示:

Apache

最后,使用以下命令刷新Magento缓存:

cd /var/www/html/magento
sudo php bin/magento cache:flush

一旦你完成,你可以继续配置Varnish。

7. 配置Varnish

Magento现已安装并配置。 现在是配置Varnish的时候了。

首先,删除/etc/varnish/default.vcl文件并从导出的Varnish配置创建一个符号链接:

sudo rm -rf /etc/varnish/default.vcl
sudo ln -s /var/www/html/magento/var/varnish.vcl /etc/varnish/default.vcl

接下来,您将需要为Varnish创建一个systemd服务文件。 您可以将varnish.service从/ lib / systemd / system /复制到/ etc / systemd / system /目录中:

sudo cp /lib/systemd/system/varnish.service /etc/systemd/system/

复制该文件后,您将需要对varnish.service文件进行一些更改:

sudo nano /etc/systemd/system/varnish.service

进行以下更改:

[Unit]
Description=Varnish HTTP accelerator
Documentation=https://www.varnish-cache.org/docs/4.1/ man:varnishd

[Service]
Type=simple
LimitNOFILE=131072
LimitMEMLOCK=82000
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m
ExecReload=/usr/share/varnish/reload-vcl
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
PrivateDevices=true

[Install]
WantedBy=multi-user.target

完成后保存文件,然后使用以下命令重新启动Varnish服务:

sudo systemctl daemon-reload
sudo systemctl reload varnish.service

如果一切正常,那么您应该能够通过在Web浏览器上输入以下URL来登录到Magento后端:

http://192.168.15.189/admin_wczta4

您还可以通过运行以下命令来检查是否启用了Varnish:

curl -I http://192.168.15.189/admin_wczta4

您应该看到Varnish已启用:

Date: Fri, 07 Jul 2017 17:10:01 GMT
Server: Apache/2.4.18 (Ubuntu)
Set-Cookie: store=default; expires=Sat, 07-Jul-2018 17:10:03 GMT; Max-Age=31536000; path=/; HttpOnly
Set-Cookie: PHPSESSID=irp2k8cmrhct0dfh18qk7ap0i4; expires=Fri, 07-Jul-2017 18:10:04 GMT; Max-Age=3600; path=/; domain=192.168.15.189; HttpOnly
Expires: Thu, 07 Jul 2016 17:10:04 GMT
Cache-Control: max-age=0, must-revalidate, no-cache, no-store
Pragma: no-cache
Location: http://192.168.15.189/admin_wczta4/?SID=irp2k8cmrhct0dfh18qk7ap0i4
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Content-Length: 0
Content-Type: text/html; charset=UTF-8
X-Varnish: 2
Age: 0
Via: 1.1 varnish-v4
Connection: keep-alive

恭喜! 您已经在Ubuntu 16.04服务器上成功配置了Magento与Varnish。

varnishstat – 查看varnish统计信息命令

varnishstat是一个查看当前varnish实例的实时运行状态信息。命令以及参数如下:

varnishstat [-1] [-f <glob>] [-h] [-j] [-l] [-n <dir>] [-N <filename>] [-t <seconds | off>] [-V ] [-X]

以下选项可用:

  • -1 不再显示不断更新的显示,而是将统计信息打印到stdout。
  • -f Field inclusion glob. Use backslash to escape characters. If the argument starts with ‘^’ it is used as an exclusion glob. Multiple -f arguments may be given, and they will be applied in order.
  • -h 显示帮助信息
  • -j 统计信息为JSON格式输出到stdout。
  • -l 列出与-f选项一起使用的可用字段。
  • -n 指定varnishd工作目录(也称为实例名称)以获取日志。如果未指定-n,则使用主机名。
  • -N 指定一个陈旧的VSM实例的文件名。使用此选项时,放弃检查被禁用。
  • -t
    在初始VSM连接返回错误之前超时。如果设置VSM连接在0.5秒钟内重试这段时间。如果为零,则仅尝试连接一次,如果不成功,将立即失败。如果设置为“关闭”,连接将不会失败,允许该实用程序启动并等待不明确地显示该Varnish实例。默认为5秒。
  • -V 打印版本信息
  • -x 输出xml格式到stdout

在服务端使用varnishstat命令之后,会出现如下输出,并且每秒刷新一次。

21+20:34:26
Hitrate ratio:        9        9        9
Hitrate avg:     0.6641   0.6641   0.6641

   636637687       499.06   337.12 client_conn - Client connections accepted
   637516286       511.04   337.58 client_req - Client requests received
   384410700       345.35   203.56 cache_hit - Cache hits
      397324         1.00         0.21 cache_hitpass - Cache hits for pass
   239345712       158.70   126.74 cache_miss - Cache misses
     4835741         0.00         2.56 backend_conn - Backend conn. success
   248259966       154.71   131.46 backend_reuse - Backend conn. reuses
      242608         0.00         0.13 backend_toolate - Backend conn. was closed
   248512413       160.70   131.59 backend_recycle - Backend conn. recycles
        1530         0.00         0.00 backend_retry - Backend conn. retry
       23931         0.00         0.01 fetch_length - Fetch with Length
   249781348       162.69   132.27 fetch_chunked - Fetch chunked
       15614         0.00         0.01 fetch_close - Fetch wanted close
         589          .            .   n_sess_mem - N struct sess_mem
          39          .            .   n_sess - N struct sess
       34325          .            .   n_object - N struct object
       34492          .            .   n_objectcore - N struct objectcore
       84074          .            .   n_objecthead - N struct objecthead
         216          .            .   n_waitinglist - N struct waitinglist
          77          .            .   n_vbc - N struct vbc
         219          .            .   n_wrk - N worker threads
      120362         0.00         0.06 n_wrk_create - N worker threads created
      576844         0.00         0.31 n_wrk_queued - N queued work requests
           1          .            .   n_backend - N backends
   239311376          .            .   n_expired - N expired objects
   213406425          .            .   n_lru_moved - N LRU moved objects
         194         0.00         0.00 losthdr - HTTP header overflows
   632853774       503.05   335.12 n_objwrite - Objects sent with write
   636660065       512.04   337.13 s_sess - Total Sessions
   637516287       511.04   337.58 s_req - Total Requests
     3283172         2.99         1.74 s_pipe - Total pipe
    10476261         3.99         5.55 s_pass - Total pass
   249820893       162.69   132.29 s_fetch - Total fetch
210331163670    169330.83    111376.73 s_hdrbytes - Total header bytes
1121952708903    992663.81    594107.97 s_bodybytes - Total body bytes
   636390701       511.04   336.99 sess_closed - Session Closed
     1746856         0.00         0.93 sess_linger - Session Linger
     5168683         2.00         2.74 sess_herd - Session herd
 38768640297     30143.36     20529.17 shm_records - SHM records
  3367627420      2570.17      1783.26 shm_writes - SHM writes
      487720         4.99         0.26 shm_flushes - SHM flushes due to overflow
    10953952        30.94         5.80 shm_cont - SHM MTX contention

第一行表示的是varnish的运行时常,上面显示是21天。

  • Hitrate ratio和Hitrate avg表示的则是在多少秒内的命中率。有几个比较重要的统计数据

  • cache-hit:缓存命中次数

  • miss-hit:未命中次数

  • worker threads:当前工作线程的数量

  • expired objects:代表过期对象的个数

  • LRU nuked objects:代表缓存可使用的内存以达上线而不得不移除的对象个数

  • LRU moved objects:代表LRU策略被移动的对象个数

  • Total header bytes:代表缓存的请求头对象的大小

  • Total body bytes:代表缓存的请求体对象大小

Varnish Cache入门介绍

需要处理大量的流量? 缓存应该是提高吞吐量最佳的方式之一。 意思是你的服务器不需要每次访问时从头开始重新生成相同的动态内容。 通过将缓存代理(如Varnish Cache)放在Web服务前面来对HTTP请求的响应加速并减少服务器工作负载,从而节省服务器资源。
Varnish工作在你的后端前面,比如Apache,Nginx还是别的什么。 如果Varnish找不到请求缓存,它会将请求转发到您的后端,然后缓存其输出。 您可以选择将这些缓存的请求存储在内存中,这会使它们的检索速度非常快。

安装

1.首先更新当前软件包并从apt安装Varnish:

  1. apt-get update
  2. apt-get upgrade
  3. apt-get install varnish

2.接下来我们要做的是编辑Varnish的守护进程选项,让它加载你的自定义配置:

  1. nano /etc/default/varnish

向下滚动到配置文件的这个块,找到当前的默认值:
/etc/default/varnish:

  1. ## Alternative 2, Configuration with VCL
  2. #
  3. # Listen on port 6081, administration on localhost:6082, and forward to
  4. # one content server selected by the vcl file, based on the request.  Use a 1GB
  5. # fixed-size cache file.
  6. #
  7. DAEMON_OPTS="-a :6081
  8.              -T localhost:6082
  9.              -f /etc/varnish/default.vcl
  10.              -S /etc/varnish/secret
  11.              -s malloc,256m"

我们需要编辑-f选项。 将其更改为:

  1. -f /etc/varnish/user.vcl

或者你喜欢的任何名称。 重要的是让您的配置独立于默认的VCL文件,因为软件包更新可能会覆盖它。
从上面的配置,我们还看到Varnish将其缓存项存储在内存中,并且设置最多使用256MB的内存。 如果您需要调整此分配,只需编辑此行上的值:

  1. -s malloc,256m

稍后再编辑这些守护进程选项。 现在,让我们来配置Varnish的后端。

基本配置

Varnish通过Varnish配置语言(VCL)进行配置。 一旦配置文件被加载,Varnish将VCL代码翻译并编译成与Varnish进程并行运行的C程序。
让我们开始定制您的VLC。 首先将default.vcl复制到一个新文件:

  1. cd /etc/varnish
  2. cp default.vcl user.vcl
  3. nano user.vcl

配置后端

1.首先,先更改varnish的后端,如Apache。 这是Varnish将请求转发到的地方,也就是要缓存的内容来源。 在我们的示例中,我们的后端Apache运行在80端口,与Varnish在同一台服务器上,因此相应地更改后端:

  1. backend default {
  2.     .host = "127.0.0.1";
  3.     .port = "80";
  4. }

2.重新启动Varnish

  1. service varnish restart

3.默认情况下,Varnish在端口6081上运行,因此在Web浏览器中,访问服务器上的端口6081:

  1. http://example.com:6081

您应该会看到您网站的首页。 要确认您看到的是网站的缓存版本,请检查返回的响应头。 您应该会看到以下两个响应头:

  1. Via: 1.1 varnish
  2. Age: 10

配置缓存生存时间(TTL)

默认情况下,Varnish将缓存请求两分钟。 如果您想调整此项,请返回并打开您的VCL文件,并通过在后端声明下面添加此代码覆盖vcl_fetch子例程:

  1. sub vcl_fetch
  2. {
  3.     set beresp.ttl = 5m;
  4. }

在从后端获取请求后调用此子例程。 您可以看到我们将对象TTL变量设置为五分钟。 值可以是秒(120秒),分钟(2分)或小时(2小时)。 您的理想TTL可能需要根据网站上的内容更新频率,网站的大小以及您需要处理的流量有所不同。

放置varnish到前端

如果上面的varnish配置能符合预期正常工作,那我们现在让Varnish和Apache交换端口,以便我们的网站的请求默认通过Varnish。
1.要更改Apache的端口,我们需要编辑/etc/apache2/ports.conf和任何存在的虚拟主机。 打开ports.conf以查找NameVirtualHost *:80和Listen 80,并把80端口更改为另一个端口。 我们将使用8080:

  1. NameVirtualHost *:8080
  2. Listen 8080

2.接下来,进入/etc/apache2/sites-available,并更改每个VirtualHost声明的开头,以更改新的端口号:

  1. <VirtualHost *:8080>

3.现在我们配置Varnish监听端口80。回到我们的守护进程选项文件(/etc/default/varnish),找到我们之前编辑的未注释的选项。 带-a标志的行指定端口号,更改为80:

  1. DAEMON_OPTS="-a :80

4.最后,我们需要编辑Varnish的后端配置,打开/etc/varnish/user.vcl并将后端配置更改为:

  1. backend default {
  2.     .host = "127.0.0.1";
  3.     .port = "8080";
  4. }

5.重启Apache和Varnish

  1. service apache2 reload
  2. service varnish restart

高级配置

VCL提供了对缓存请求的多种配置,并且可以根据需要对varnish进行一些自定义修改。 让我们来看一些常见的VCL修改,以及一些提示和技巧。

跳过某些请求的缓存

如果你的服务器运行多个网站,通常想要从Varnish的缓存中排除它们中的一些。 为此,我们将通过Varnish的请求对象来获取有关请求的信息,并根据条件告诉varnish将请求直接传递给后端。
我们需要在我们的VCL文件中覆盖vcl_recv子例程,每次Varnish收到请求时都运行它,然后添加一个条件:

  1. sub vcl_recv
  2. {
  3.     if (req.http.host ~ "example.com" ||
  4.         req.url ~ "^/admin")
  5.     {   
  6.         return (pass);
  7.     }
  8. }

你可以看到我们设置的不想缓存的两个条件。 第一个是针对example.com的任何请求,第二个是针对以/admin开头的任何URI请求。 如果这些都满足,Varnish不会缓存请求。

删除cookies

如前所述,如果Varnish检测到您的网站正在设置Cookie,它会假设您的网站需要与这些Cookie进行交互,并相应地显示动态内容,导致Varnish将不会缓存这些网页。 我们可以通过在Varnish的req.http对象清空Cookies。
将它添加到我们的VLC中的vcl_recv的底部:

  1. unset req.http.Cookie;

您可能会发现特定的Cookie对于显示内容很重要,或者用来确定您的用户是否已登录。 在这种情况下,您可能不想显示缓存的内容,只要将用户直接发送到后端。
对于这种情况,我们将检查req.http.Cookie一个名为“logged_in”的cookie,如果我们找到它,将请求直接传递到后端。 这里是我们整个vcl_recv子例程:

  1. sub vcl_recv
  2. {
  3.     if (req.http.host ~ "example.com" ||
  4.         req.url ~ "^/admin" ||
  5.         req.http.Cookie ~ "logged_in")
  6.     {   
  7.         return (pass);
  8.     }
  9.  
  10.     unset req.http.Cookie;
  11. }

缓存POST还是不缓存POST?

很可能你不想缓存POST请求,因为他们可能需要与后端交互以收集动态数据或设置用户的会话。 在上面的例子中,我们选择不缓存请求,如果用户登录。我们需要确保他们可以登录。 一个简单的方法是跳过POST请求。
让我们将这个条件添加到我们现有的在vcl_recv中的return(pass)块:

  1. if (req.http.host ~ "example.com" ||
  2.     req.url ~ "^/admin" ||
  3.     req.http.Cookie ~ "logged_in" ||
  4.     req.request == "POST")
  5. {   
  6.     return (pass);
  7. }

最终VCL文件

/etc/varnish/user.vcl:

  1. backend default {
  2.     .host = "127.0.0.1";  # IP address of your backend (Apache, nginx, etc.)
  3.     .port = "8080";       # Port your backend is listening on
  4.     .probe = {
  5.         .url = "/";
  6.         .timeout = 34ms;
  7.         .interval = 1s;
  8.         .window = 10;
  9.         .threshold = 8;
  10.     }
  11. }
  12.  
  13. sub vcl_recv
  14. {
  15.    # Do not cache example.com, the admin area,
  16.    # logged-in users or POST requests
  17.    if (req.http.host ~ "example.com" ||
  18.         req.url ~ "^/admin" ||
  19.         req.http.Cookie ~ "logged_in" ||
  20.         req.request == "POST")
  21.     {
  22.         return (pass);
  23.     }
  24.  
  25.     # Don’t allow cookies to affect cachability
  26.     unset req.http.Cookie;
  27.  
  28.     # Set Grace Time to one hour
  29.     set req.grace = 1h;
  30. }
  31.  
  32. sub vcl_fetch
  33. {
  34.     # Set the TTL for cache object to five minutes
  35.     set beresp.ttl = 5m;
  36.  
  37.     # Set Grace Time to one hour
  38.     set beresp.grace = 1h;
  39. }

为wordpress增加手机主题

为了方便手机查阅博客的资料,今天为博客增加了手机浏览的支持。需要一个插件和一个手机主题即可完成。
插件:http://wordpress.org/extend/plugins/wpms-mobile-edition/
手机主题:http://wordpress.org/extend/themes/carrington-mobile
由于我的博客使用了varnish缓存,所以还需要在default.vcl配置文件的sub vcl_recv中增加对User-Agent的判断。

  1. if (req.http.User-Agent ~  "(2.0 MMP|240×320|400X240|AvantGo|BlackBerry|Blazer|Cellphone|Danger|DoCoMo|Elaine/3.0|EudoraWeb|Googlebot-Mobile|hiptop|IEMobile|KYOCERA/WX310K|LG/U990|MIDP-2.|MMEF20|MOT-V|NetFront|Newt|Nintendo Wii|Nitro|Nokia|Opera Mini|Palm|PlayStation Portable|portalmmm|Proxinet|ProxiNet|SHARP-TQ-GX10|SHG-i900|Small|SonyEricsson|Symbian OS|SymbianOS|TS21i-10|UP.Browser|UP.Link|webOS|Windows CE|WinWAP|YahooSeeker/M1A1-R2D2|iPhone|iPod|Android|BlackBerry9530|LG-TU915 Obigo|LGE VX|webOS|Nokia5800)") {
  2.            return (pass);
  3. }