Linux下Varnish緩衝的配置最佳化

來源:互聯網
上載者:User

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

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

Varnish採用了“Visual Page Cache”技術,在記憶體的利用上,Varnish比Squid具有優勢,它避免了Squid頻繁在記憶體、磁碟中分頁檔,效能要比Squid高。

通過Varnish管理連接埠,可以使用Regex快速、批量地清除部分緩衝,這一點是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 如果前端有多重反向 Proxy,這樣可以擷取用戶端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管理連接埠,使用Regex批量清除緩衝
清除所有緩衝
/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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.