安裝varnish,安裝包需要到官網下載http://www.varnish-cache.org/releases/index.html
varnish的程序環境:
/etc/varnish/varnish.params:配置varnish服務進程的工作特性,例如監聽的地址、端口及緩存機制等; /etc/varnish/default.vcl:配置各Child/Cache線程的工作屬性; /usr/sbin/varnishd:ansible的主程序 /usr/bin/varnishadm:命令行接口工具 共享內存日志的交互工具: /usr/bin/varnishhist /usr/bin/varnishlog /usr/bin/varnishncsa /usr/bin/varnishstat /usr/bin/varnishtop /usr/bin/varnishtest:測試工具程序 /usr/sbin/varnish_reload_vcl:vcl配置文件重載程序,在varnishadm命令中有一個內置命令vcl.load可達到同樣效果 [root@localhost ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082 systemd unit file: /usr/lib/systemd/system/varnish.service:varnish服務 /usr/lib/systemd/system/varnishlog.service:日志持久的服務 /usr/lib/systemd/system/varnishncsa.service:日志持久的服務
varnish的緩存存儲機制:
malloc [,size]:內存存儲,size用于定義空間大小;重啟后所有緩存項失效; file [,path[,size[,granularity]]]:文件格式存儲,是一個黑盒文件(對用戶不可見,其組織格式,用戶是無法參與的),重啟后所有緩存項失效; persistent [path,size]:文件格式存儲,黑盒文件,重啟后所有緩存項有效,但目前在實驗階段;
varnish程序的選項:
/etc/varnish/varnish.params文件的變量和/usr/lib/systemd/system/varnish.service文件是相聯系的 程序選項:/etc/varnish/varnish.params文件 -a address[:port][,address[:port][...],默認為6081端口; -T address[:port],默認為6082端口; -s [name=]type[,options],定義緩存存儲機制; -u user -g group -f config:VCL配置文件; -F:運行于前臺; ... 運行時參數:/etc/varnish/varnish.params文件, DEAMON_OPTS DAEMON_OPTS="-p thread_pool_min=5 -p thread_pool_max=500 -p thread_pool_timeout=300" -p param=value:設定運行參數及其值; 可重復使用多次; -r param[,param...]: 設定指定的參數為只讀狀態;
varnishadm -S /etc/varnish/secret -T [ADDRESS:]PORT 有以下內置命令
help [<command>] ping [<timestamp>] auth <response> quit banner status:顯示當前varnish服務狀態 start:啟動進程 stop:停止進程 vcl.load <configname> <filename>:手動加載一個配置文件版本(原文件修改了) vcl.inline <configname> <quoted_VCLstring> vcl.use <configname>:指定要使用的配置列表中的某個配置文件(版本) vcl.discard <configname>:刪除某個版本的配置文件 vcl.list:列出編譯成功的配置列表 param.show [-l] [<param>]:列出可使用的配置參數 param.set <param> <value>:修改某個配置參數 eg:param.set thread_pool_max 1024 panic.show panic.clear storage.list vcl.show [-v] <configname> backend.list [<backend_expression>]:列出后端服務器列表 backend.set_health <backend_expression> <state>:定義后端主機的健康狀態的檢查機制 ban <field> <operator> <arg> [&& <field> <oper> <arg>]... ban.list 配置文件相關: vcl.list vcl.load:裝載,加載并編譯; vcl.use:激活; vcl.discard:刪除; vcl.show [-v] <configname>:查看指定的配置文件的詳細信息; 運行時參數: param.show -l:顯示列表; param.show <PARAM> param.set <PARAM> <VALUE> 緩存存儲: storage.list 后端服務器: backend.list
VCL:
varnish的規則配置語言,是“域”專有類型的配置語言 VCL有多個狀態引擎,狀態之間存在相關性,但彼此間互相隔離;每個狀態引擎可使用return(x)指明關聯至哪個下一級引擎;如:vcl_hash --> return(hit) --> vcl_hit
vcl流程圖
狀態引擎切換機制:
request報文由vcl_recv接收,response報文由vcl_deliber發送,幾種常用切換如下: (1)vcl_recv --> vcl_hash --> vcl_hit --> vcl_deliver (2)vcl_recv --> vcl_hash --> vcl_miss --> vcl_backend_fetch --> vcl_backend_response(vcl_backend_error) --> vcl_dliver (3)vcl_recv --> vcl_hash --> vcl_purge --> vcl_synth (4)vcl_recv --> vcl_hash --> vcl_pipe 兩個特殊的引擎: vcl_init:在處理任何請求之前要執行的vcl代碼:主要用于初始化VMODs; vcl_fini:所有的請求都已經結束,在vcl配置被丟棄時調用;主要用于清理VMODs;
vcl的語法格式:
(1) VCL files start with vcl 4.0; 以下語法適合4.0,需放在default.vcl文件第一行 (2) //, # and /* foo */ for comments; 用于注釋 (3) Subroutines(子程序) are declared with the sub keyword;子例程使用sub關鍵字進行聲明,例如sub vcl_recv { ... } (4) No loops, state-limited variables;不支持循環,支持限于引擎的內建的狀態變量(req* , bereq* , obj* , ...) (5) Terminating statements with a keyword for next action as argument of the return() function, i.e.: return(action); (6) Domain-specific; 域專用狀態
The VCL Finite(有限的) State Machine(vcl的有限狀態機)
(1) Each request is processed separately; 每個請求都被單獨處理 (2) Each request is independent from others at any given time; 每個請求在任何時間與其他請求之間都是隔離的 (3) States are related(關聯的), but isolated(分離的); (4) return(action); exits one state and instructs(命令) Varnish to proceed to the next state; 狀態切換是靠return完成的 (5) Built-in VCL code is always present and appended(附加) below your own VCL; 內建vcl代碼一直有效并附加在你自定義的vcl之后(在varnishadm中使用vcl.show查看)
VCL Built-in Functions and Keywords(vcl的內建函數和keyword)
函數: regsub(str, regex, sub):基于"str"字符串,被regex匹配到的字符串替換為"sub" regsuball(str, regex, sub):全局替換 ban(boolean expression) hash_data(input) synthetic(str) Keywords: call subroutine return(action) new set unset 操作符: ==, !=, ~, >, >=, <, <= 邏輯操作符:&&, ||, ! 變量賦值:= 示例:如下圖
varnish變量類型:
內建變量: req.*:request,表示由客戶端發來的請求報文相關; req.http.* req.http.User-Agent, req.http.Referer, ... bereq.*:由varnish主機發往后端主機的httpd請求相關; bereq.http.* beresp.*:由后端主機響應給varnish主機的響應報文相關; beresp.http.* resp.*:由varnish響應給client相關; obj.*:存儲在緩存空間中的緩存對象的屬性;只讀; 常用變量: bereq.*, req.*: bereq.http.HEADERS:http請求報文的某個首部 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:此對象從緩存中命中的次數; obj.ttl:對象的ttl值 server.* server.ip server.hostname client.* client.ip 用戶自定義: set unset
示例1:強制對某類資源的請求不檢查緩存:
sub vcl_recv { if (req.url ~ "(?i)^/(login|admin)"){ return(pass); (login或admin開頭的URL直接miss,不查詢緩存) } } 此列不能再瀏覽器中測試,因為瀏覽器會在miss后varnish后直接請求后端主機,用下面命令查看 [root@keepalived2 ~]# curl -I http://10.1.51.10/login/index.html
示例2:對于特定類型的資源,例如公開的圖片等,取消其私有標識,并強行設定其可以由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; } } }
緩存對象的修剪(僅授權管理員):purge(清理單個緩存), ban (清理能被模式匹配到的所有緩存)
示例1:
sub vcl_recv { if (req.method == "PURGE") { return (purge); (定義請求方法為PURGE) } } sub vcl_purge { return(synth(200,"purged")); (當purge請求時,返回自定義狀態) } 需要使用curl命令測試,先用-X選項指定用PURGE方法請求,此時會清理對應請求的緩存,再用-I選項時可看到結果為miss。
示例2:限制指定用戶可使用purge;
acl purgers { "127.0.0.0"/8; "10.1.0.0"/16; } (定義預習使用purge的用戶) sub vcl_recv { if (req.method == "PURGE") { if (!client.ip ~ purgers) { return(synth(405,"Purging not allowed for " + client.ip)); } return(purge); } } 如果非指定用戶(ip)訪問,會返回405狀態碼(curl命令測試)
director輪詢
(1)不同請求響應不同內容
backend default { .host = "10.1.51.20"; .port = "80"; } backend appsrv { .host = "10.1.51.30"; .port = "80"; } sub vcl_recv { if (req.url ~ "(?i)\.php$") {(后綴為php的則訪問主機appsrv,其他訪問default) set req.backend_hint = appsrv; }else { set req.backend_hint = default; } }
(2)輪詢,負載均衡效果
import directors; backend default { .host = "10.1.51.20"; .port = "80"; } backend appsrv { .host = "10.1.51.30"; .port = "80"; } sub vcl_init { new websrvs = directors.round_robin(); websrvs.add_backend(default); websrvs.add_backend(appsrv); } sub vcl_recv { set req.backend_hint = websrvs; } 使用curl命令進行測試可以更好的看到效果,瀏覽器會在命中后,在緩存有效期內都只會返回第二次命中的后端主機的記錄。
后端主機的健康檢測:
.probe:定義健康狀態檢測方法; .url:檢測時請求的URL,默認為”/"; .request:發出的具體請求; .request = "GET /.healthtest.html HTTP/1.1" "Host: www.magedu.com" "Connection: close" .window:基于最近的多少次檢查來判斷其健康狀態; .threshold:最近.window中定義的這么多次檢查中至有.threshhold定義的次數是成功的;如.window=5 .threshhold=3,那5次檢測中至少3次成功的才為成功 .interval:檢測頻度; .timeout:超時時長; .expected_response:期望的響應碼,默認為200;
示例:
probe check { .url = "/.healthcheck.html"; (在根目錄中定義一個測試網頁) .window = 5; .threshold = 4; .interval = 2s; .timeout = 1s; } backend default { .host = "10.1.51.20"; .port = "80"; .probe = check; } backend appsrv { .host = "10.1.51.30"; .port = "80"; .probe = check; } 注意probe放置的位置,在最前面是,如果測試失敗則該主機后面的網頁不能訪問 在varnishadm中使用內置命令backend.list可以查看命中(測試)的結果,可使用backend.set_health命令手動設置后端主機的健康狀態(sick,healthy 永久哦)
varnish的運行參數:param.show -l查看所有參數
線程相關的參數: 在線程池內部,其每一個請求由一個線程來處理; 其worker線程的最大數決定了varnish的并發響應能力; thread_pools:Number of worker thread pools. 最好小于或等于CPU核心數量; thread_pool_max:The maximum number of worker threads in each pool.每個線程池的最大線程數 thread_pool_min:The minimum number of worker threads in each pool. 額外意義為“最大空閑線程數”; 最大并發連接數=thread_pools * thread_pool_max thread_pool_timeout:Thread idle threshold. Threads in excess of thread_pool_min, which have been idle for at least this long, will be destroyed.每個線程空閑超時時長,超時就殺掉,但是不能低于最小線程數; thread_pool_add_delay:Wait at least this long after creating a thread. thread_pool_destroy_delay:Wait this long after destroying a thread. 設置方式:在varnishadm中 vcl.param 永久有效的方法: varnish.params文件最后一行 DEAMON_OPTS="-p PARAM1=VALUE -p PARAM2=VALUE"
varnish日志區域:
1、varnishstat - Varnish Cache statistics -1 :將某時刻的狀態全部列出 -1 -f FILED_NAME -l:可用于-f選項指定的字段名稱列表; 示例: # varnishstat -1 -f MAIN.cache_hit -f MAIN.cache_miss 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 ReqURL:/ -I ReqURL:/ 3、varnishlog - Display Varnish logs 4、 varnishncsa - Display Varnish logs in Apache / NCSA combined log format
原創文章,作者:pao,如若轉載,請注明出處:http://www.www58058.com/59342