Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

Varnish 安裝與 VCL 配置:記憶體級快取實作

一、兩種常見拓撲

Varnish 上線通常有兩種模式:

第一種:Nginx(負責負載平衡)+ Varnish(負責快取)+ Web 後端。

第二種:Varnish(同時負責快取與負載)+ Web 後端。

二、Varnish 的特性

Varnish 以記憶體作為共享容器,能快取多少完全取決於你給它多少記憶體。相比以硬碟為主的 Squid,它效率高得多,特別適合那些「常被查詢且變動不大」的靜態內容。

在第一種架構裡,Nginx 把圖片與靜態文字轉給 Varnish,動態內容則直接轉給後端 Web 的 8080 連接埠。不過要不要多這一層,得看你的伺服器資源與內容型態——如果 Nginx 不需要做反向代理去支援一堆後台應用,單靠 proxy_cache 也能做本機快取,它存在硬碟上,效能與 Squid 差不多,但穩定性與易用性更好。

三、編譯安裝

先建立執行身分與目錄:

groupadd www
useradd -g www www
mkdir -p /var/vcache
chown -R www:www /var/vcache

mkdir -p /var/log/varnish
chmod +w /var/log/varnish
chown -R www:www /var/log/varnish

接著編譯:

tar zxvf varnish-1.1.2.tar.gz
cd varnish-1.1.2
./configure --prefix=/usr/local/varnish
make && make install

四、撰寫 VCL

vi /usr/local/varnish/vcl/conf
backend default {
    # 反向代理的後端 WEB,可以是本機也可以是別台
    .host = "192.168.0.151";
    .port = "81";
}

acl purge {
    # 允許這些來源用 PURGE 方法清快取
    "localhost";
    "127.0.0.1";
    "192.168.1.0"/24;
}

sub vcl_recv {
    if (req.request == "PURGE") {
        if (!client.ip ~ purge) {
            error 405 "Not allowed.";
        }
        return(lookup);
    }

    if (req.http.host ~ "^blog.s135.com") {
        set req.backend = default;
        if (req.request != "GET" && req.request != "HEAD") {
            return(pipe);
        } else {
            return (lookup);
        }
    } else {
        error 404 "Not in cache";
        return(lookup);
    }
}

sub vcl_hit {
    if (req.request == "PURGE") {
        set obj.ttl = 0s;
        error 200 "Purged.";
    }
}

sub vcl_miss {
    if (req.request == "PURGE") {
        error 404 "Not in cache.";
    }
}

sub vcl_fetch {
    if (req.request == "GET" && req.url ~ "\.(txt|js)$") {
        set obj.ttl = 3600s;   # txt 與 js 快取一小時
    } else {
        set obj.ttl = 30d;     # 其餘快取一個月
    }
}

這樣設定的理由:Varnish 對 GET 與 HEAD 做快取,POST 則直接穿透到後端。因為 POST 通常是往伺服器送資料、需要接收與處理,快取它沒有意義。

五、啟動與日誌

ulimit -SHn 51200
/usr/local/varnish/sbin/varnishd -a :80 -b 192.168.0.151:81 \
  -p thread_pool_max=1500 -p thread_pools=5 -p listen_depth=512 \
  -w 1,10000,120

把訪問日誌寫入檔案:

/usr/local/varnish/bin/varnishncsa -n /var/vcache -w /var/log/varnish/varnish.log &

完成後即可用 varnishstat 看狀態,並實際請求測試。整體架構是 Varnish 監聽 80,資料來源轉向監聽 81 的 Apache。

Copyright © Linux教程網 All Rights Reserved