Linux下Varnish緩存的配置優化


Varnish是一款高性能的開源HTTP加速器,挪威最大的在線報紙 Verdens Gang 使用3台Varnish代替了原來的12台Squid,性能比以前更好。

但與老牌的squid相比,各有各的優劣勢,網上大量的相對比較只是在其個人對自己熟悉的應用的最大使用上的發揮而已,可能squid到了有能力的人手上才足以發揮最強大的威力

Varnish采用了“Visual Page Cache”技術,在內存的利用上,Varnish比Squid具有優勢,它避免了Squid頻繁在內存、磁盤中交換文件,性能要比Squid高。

通過Varnish管理端口,可以使用正則表達式快速、批量地清除部分緩存,這一點是Squid不能具備的。 

本人就varnish的一些見解與配置方法做簡單的介紹與筆記

實驗環境:Red Hat Enterprise Linux Server release 5.4 (Tikanga) 
內核2.6.18-164.el5
yum install pcre-devel     ##預先安裝一個軟件包,不然會提示錯誤
tar zxvf varnish-2.1.3.tar.gz
cd varnish-2.1.3 
./configure --prefix=/usr/local/varnish-2.1.3
make && make install
編輯配置文件,有模版,但太多注釋,最好自己新建一個
vim /usr/local/varnish-2.1.3/etc/varnish/varnish.conf   
############下面附上配置文件的內容及注釋#######################
#http請求處理過程
#1,receive請求入口狀態,根據vcl判斷pass還是lookup本地查詢
#lookup,在hash表中查找數據,若找到則進入hit狀態,否則進入fetch狀態
#pass,選擇后台,進入fetch狀態
#fetch,對請求進行后端的獲取,發送請求,獲得數據,並進行本地存儲
#deliver,將數據發送給客戶端,進入done
#done,處理結束
##########配置后端服務器##############
backend linuxidc01 {
      .host = "192.168.1.142";
      .port = "7070";
      .probe = {
      .timeout = 5s;         
      .interval = 2s;          
      .window = 10;         
      .threshold = 8;     
      }
   }
backend linuxidc02 {
      .host = "192.168.1.141";
      .port = "7070";
      .probe = {
      .timeout = 5s;
      .interval = 2s;
      .window = 10;
      .threshold = 8;
      }
   }
##############配置后端服務器組,進行健康檢測6秒,使用random方式設置權重######## 
#########另一種方式round-robin則默認輪詢機制####################
director linuxidc15474 random
        { .retries = 6;
            { .backend = linuxidc02;
              .weight = 2;
             }
            { .backend = linuxidc01;
               .weight = 2;
            } 
        }
##########定義訪問列表,允許下列地址清除varnish緩存#######################
acl local  {
         "localhost";
         "127.0.0.1";
          }
########從url判斷針對哪類后面服務器及緩存配置############################
sub vcl_recv 
{
       if (req.http.host ~ "^linuxidc15474.vicp.net")  #匹配域名跳轉后台服務器
            { set req.backend = linuxidc15474; }
         else { error 404 "Unknown HostName!"; }
        if (req.request == "PURGE")    #不允許非訪問控制列表內的IP清除varnish緩存 
             { if (!client.ip ~ local)
                 {
                  error 405 "Not Allowed.";  
                  return (lookup);   
                 }
             }
        #清除url中有jpg等文件的cookie
        if (req.request == "GET" && req.url ~ "\.(jpg|png|gif|swf|jpeg|ico)$")
            {
              unset req.http.cookie;
             }   
        #判斷req.http.X-Forwarded-For 如果前端有多重反向代理,這樣可以獲取客戶端IP地址。
        if (req.http.x-forwarded-for)
           {
              set req.http.X-Forwarded-For = req.http.X-Forwarded-For ", " client.ip;
           }
        else { set req.http.X-Forwarded-For = client.ip; }
##varnish實現圖片的防盜鏈
#        if (req.http.referer ~ "http://.*) 
#          {
#             if ( !(req.http.referer ~ "http://.*vicp\.net" ||
#                   req.http.referer ~ "http://.*linuxidc15474\.net" ) )
#                 {
#                   set req.http.host = "linuxidc15474.vicp.net";
#                   set req.url = "/referer.jpg"; 
#                 }
#              return(lookup);
#          }
#         else {return(pass);}
       if (req.request != "GET" && 
           req.request != "HEAD" && 
           req.request != "PUT" && 
           req.request != "POST" && 
           req.request != "TRACE" && 
           req.request != "OPTIONS" && 
           req.request != "DELETE") 
        { return (pipe); }
        #對非GET|HEAD請求的直接轉發給后端服務器
        if (req.request != "GET" && req.request != "HEAD")
            { return (pass); }
        ##對GET請求,且url里以.php和.php?結尾的,直接轉發給后端服務器
        if (req.request == "GET" && req.url ~ "\.(php)($|\?)")
            { return (pass); }
        ##對請求中有驗證及cookie,直接轉發給后端服務器
        if (req.http.Authorization || req.http.Cookie)
            { return (pass);}
         {
           ##除以上的訪問請求,從緩存中查找
           return (lookup);
         }
       ##指定的font目錄不進行緩存
       if (req.url ~ "^/fonts/")
           { return (pass); }
}
sub vcl_pipe 
            { return (pipe); }
##進入pass模式,請求被送往后端,后端返回數據給客戶端,但不進入緩存處理 
sub vcl_pass 
            { return (pass); }
sub vcl_hash
      {
          set req.hash += req.url; 
        if (req.http.host) 
           { set req.hash += req.http.host; } 
        else { set req.hash += server.ip; } 
      return (hash); 
      }
##在lookup后如果在cache中找到請求的緩存,一般以下面幾個關鍵詞結束
sub vcl_hit 
          { 
              if (!obj.cacheable) 
                { return (pass); } 
               return (deliver); 
          } 
##lookup后沒有找到緩存時調用,以下面幾個關鍵詞結束,及調用fetch參數重新測試是否加入緩存
sub vcl_miss 
     { return (fetch); }
#讓varnish服務器緩存的類型,從后端取得數據后調用
sub vcl_fetch 
  {    if (!beresp.cacheable) 
            { return (pass); } 
        if (beresp.http.Set-Cookie) 
           { return (pass); } 
       ##WEB服務器指明不緩存的內容,varnish服務器不緩存
       if (beresp.http.Pragma ~ "no-cache" || beresp.http.Cache-Control ~ "no-cache" || beresp.http.Cache-Control ~ "private") 
          { return (pass); }
       ##對訪問中get有包含jpg,png等格式的文件進行緩存,緩存時間為7天,s為秒
      if (req.request == "GET" && req.url ~ "\.(js|css|mp3|jpg|png|gif|swf|jpeg|ico)$") 
         { set beresp.ttl = 7d; }
      ##對訪問get中包含htm等靜態頁面,緩存300秒 
      if (req.request == "GET" && req.url ~ "\/[0-9]\.htm$") 
         { set beresp.ttl = 300s; }
           return (deliver); 
   }
####添加在頁面head頭信息中查看緩存命中情況########
sub vcl_deliver 
 {
       set resp.http.x-hits = obj.hits ; 
       if (obj.hits > 0) 
              { set resp.http.X-Cache = "HIT cqtel-bbs"; } 
       else { set resp.http.X-Cache = "MISS cqtel-bbs"; } 
  }
#########################以上為 varnish的配置文件##########################
 
創建用戶:
groupadd www
useradd www -g www
創建 varnish_cache的緩存位置
mkdir /data/varnish_cache
啟動varnish
ulimit -SHn 8192   ####設置文件描述符,因為我的機子性能並不好,可以按照自己的配置去設置
/usr/local/varnish-2.1.3/sbin/varnishd -u www -g www -f /usr/local/varnish-2.1.3/etc/varnish/varnish.conf -a 0.0.0.0:80 -s file,/data/varnish_cache/varnish_cache.data,100M -w 1024,8192,10 -t 3600 -T 127.0.0.1:3500
####-u 以什么用運行 -g 以什么組運行 -f varnish配置文件 -a 綁定IP和端口 -s varnish緩存文件位置與大小 -w 最小,最大線程和超時時間 -T varnish管理端口,主要用來清除緩存
#結束varnishd進程
pkill varnishd
啟動varnishncsa用來將Varnish訪問日志寫入日志文件:
/usr/local/varnish-2.1.3/bin/varnishncsa -w /data/logs/varnish.log &
每天0點運行,按天切割Varnish日志,生成一個壓縮文件,同時刪除上個月舊日志的腳本(/var/logs/cutlog.sh):
vim /usr/local/varnish-2.1.3/etc/varnish/cut_varnish_log.sh
寫入以下腳本:
#!/bin/sh
# This file run at 00:00
date=$(date -d "yesterday" +"%Y-%m-%d")
pkill -9 varnishncsa
mv /data/logs/varnish.log /data/logs/${date}.log
/usr/local/varnish-2.1.3/bin/varnishncsa  -w /data/logs/varnish.log &
mkdir -p /data/logs/varnish/
gzip -c /data/logs/${date}.log > /data/logs/varnish/${date}.log.gz
rm -f /data/logs/${date}.log
rm -f /data/logs/varnish/$(date -d "-1 month" +"%Y-%m*").log.gz
定時任務:
crontab -e
00 00 * * * /usr/local/varnish-2.1.3/etc/varnish/cut_varnish_log.sh
 
優化Linux內核參數
vi /etc/sysctl.conf
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.ip_local_port_range = 5000    65000
使配置生效
/sbin/sysctl -p
 
通過Varnish管理端口,使用正則表達式批量清除緩存
清除所有緩存
/usr/local/varnish-2.1.3/bin/varnishadm -T 127.0.0.1:3500 url.purge *$
清除image目錄下所有緩存
/usr/local/varnish-2.1.3/bin/varnishadm -T 127.0.0.1:3500 url.purge /image/
127.0.0.1:3500 為被清除緩存服務器地址 www.linuxidc.com 為被清除的域名 /static/image/tt.jsp 為被清除的url地址列表
/usr/local/varnish-2.1.3/bin/varnishadm -T 127.0.0.1:3500 purge "req.http.host ~ www.linuxidc.com$ && req.url ~ /static/image/tt.jsp"


+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
一個清除Squid緩存的PHP函數
<?php   
function purge($ip, $url)   
{   
    $errstr = '';   
    $errno = '';   
    $fp = fsockopen ($ip, 80, $errno, $errstr, 2);   
    if (!$fp)   
    {   
         return false;   
    }   
    else  
    {   
        $out = "PURGE $url HTTP/1.1\r\n";   
        $out .= "Host:blog.s135.com\r\n";   
        $out .= "Connection: close\r\n\r\n";   
        fputs ($fp, $out);   
        $out = fgets($fp , 4096);   
        fclose ($fp);   
        return true;   
    }   
}   
  
purge("192.168.0.4", "/index.php");   
?> 
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 
配置開機自動啟動Varnish
vim /etc/rc.d/rc.local
在末行寫入以下內容:
ulimit -SHn 8192
/usr/local/varnish-2.1.3/sbin/varnishd -u www -g www -f /usr/local/varnish-2.1.3/etc/varnish/varnish.conf -a 0.0.0.0:80 -s file,/data/varnish_cache/varnish_cache.data,100M -w 1024,8192,10 -t 3600 -T 127.0.0.1:3500
/usr/local/varnish-2.1.3/bin/varnishncsa -w /data/logs/varnish.log &
查看Varnish服務器連接數與命中率:
/usr/local/varnish-2.1.3/bin/varnishstat


以上為varnish的狀態,
1675         0.00         0.06 Client requests received   為服務端接收的客戶端請求次數
179         0.00         0.01 Cache hits    為命中緩存,從緩存中取得數據返回給客戶端的次數,即命中率
11         0.00         0.00 Cache misses  為跳過pass緩存,從后端服務應用中取得數據返回給用戶的次數
用help看看可以使用哪些Varnish命令:
/usr/local/varnish-2.1.3/bin/varnishadm -T 127.0.0.1:3500 help


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM