天天看點

Varnish緩存的配置優化

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 kangta01 {       .host = "192.168.1.142";       .port = "7070";       .probe = {       .timeout = 5s;                .interval = 2s;                 .window = 10;                .threshold = 8;            }    } backend kangta02 {       .host = "192.168.1.141";       .port = "7070";       .probe = {       .timeout = 5s;       .interval = 2s;       .window = 10;       .threshold = 8;       }    } ##############配置後端伺服器組,進行健康檢測6秒,使用random方式設定權重########  #########另一種方式round-robin則預設輪詢機制#################### director kangta15474 random         { .retries = 6;             { .backend = kangta02;               .weight = 2;              }             { .backend = kangta01;                .weight = 2;             }          } ##########定義通路清單,允許下列位址清除varnish緩存####################### acl local  {          "localhost";          "127.0.0.1";           } ########從url判斷針對哪類後面伺服器及緩存配置############################ sub vcl_recv  {        if (req.http.host ~ "^kangta15474.vicp.net")  #比對域名跳轉背景伺服器             { set req.backend = kangta15474; }          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://.*kangta15474\.net" ) ) #                 { #                   set req.http.host = "kangta15474.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 *$ 清除p_w_picpath目錄下所有緩存 /usr/local/varnish-2.1.3/bin/varnishadm -T 127.0.0.1:3500 url.purge /p_w_picpath/ 127.0.0.1:3500 為被清除緩存伺服器位址 www.kangta.com 為被清除的域名 /static/p_w_picpath/tt.jsp 為被清除的url位址清單 /usr/local/varnish-2.1.3/bin/varnishadm -T 127.0.0.1:3500 purge "req.http.host ~ www.kangta.com$ && req.url ~ /static/p_w_picpath/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

轉載于:https://blog.51cto.com/aceruser/679339

繼續閱讀