利用varnish構建httpd緩存服務器

varnish如何存儲緩存對象:

    file: 單個文件;不支持持久機制;

    malloc: 緩存在內存中;

    persistent:基于文件的持久存儲;(此方式不建議使用)

vcl:配置緩存系統的緩存機制;【線程中緩存功能的工作機制】

一、在vs2和vs3上安裝http

寫入文件,內容一個為on vs2,另一個為on vs3

[root@vs2 ~]# yum install http
[root@vs2 ~]# for i in {1..10}; do echo "web$i on vs2" > /var/www/html/test$i.html; done
[root@vs2 ~]# ls /var/www/html/
test10.html  test2.html  test4.html  test6.html  test8.html
test1.html   test3.html  test5.html  test7.html  test9.html
[root@vs2 ~]# systemctl start httpd.service

二、安裝varnish(在centos7上安裝4.0.3版本)

[root@vs1 ~]# yum install varnish

三、varnish主程序的配置文件

[root@vs1 ~]# vim /etc/varnish/varnish.params 

# Varnish environment configuration description. This was derived from
# the old style sysconfig/defaults settings

# Set this to 1 to make systemd reload try to switch vcl without restart.
RELOAD_VCL=1

# Main configuration file. You probably want to change it.
VARNISH_VCL_CONF=/etc/varnish/default.vcl    #讀取vcl配置文件的位置

# Default address and port to bind to. Blank address means all IPv4
# and IPv6 interfaces, otherwise specify a host name, an IPv4 dotted
# quad, or an IPv6 address in brackets.
# VARNISH_LISTEN_ADDRESS=192.168.1.5
VARNISH_LISTEN_PORT=6081    #監聽的服務端口為6081

# Admin interface listen address and port
VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1    #監聽的管理地址為本機
VARNISH_ADMIN_LISTEN_PORT=6082    #監聽的管理端口為6082

# Shared secret file for admin interface
VARNISH_SECRET_FILE=/etc/varnish/secret    #密鑰文件位置

# Backend storage specification, see Storage Types in the varnishd(5)
# man page for details.
VARNISH_STORAGE="file,/var/lib/varnish/varnish_storage.bin,1G"    #緩存以文件的方式的存儲位置和大小
#VARNISH_STORAGE="malooc,256M"    #以內存方式緩存,緩存大小為256M

# Default TTL used when the backend does not specify one
VARNISH_TTL=120    #聯系后端服務器超時時長

# User and group for the varnishd worker processes
VARNISH_USER=varnish    #主進程所使用的用戶
VARNISH_GROUP=varnish    #主進程所使用的組

# Other options, see the man page varnishd(1)    #進程選項,線程池的最大值最小值和超時時長
DAEMON_OPTS="-p thread_pool_min=5 -p thread_pool_max=500 -p thread_pool_timeout=300"

四、varnish的命令行管理工具

[root@vs1 ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082
help      
help [<command>]    #獲取幫助信息
ping [<timestamp>]    #測試服務器是否正常
auth <response>    #
quit                #退出
banner
status            #顯示服務器狀態信息
start            #啟動子進程
stop            #停止子進程
vcl.load <configname> <filename>    #載入哪個文件為配置文件
vcl.inline <configname> <quoted_VCLstring>
vcl.use <configname>                #使用哪個vcl文件
vcl.discard <configname>            #刪除哪個vcl文件
vcl.list                     #列出所有可用的vcl文件
param.show [-l] [<param>]            #顯示運行時參數
param.set <param> <value>                
panic.show                     #顯示恐慌信息,顯示進程或子進程上次掛掉的原因
panic.clear                                        #清除恐慌信息
storage.list                                        #顯示緩存信息
vcl.show [-v] <configname>                        #顯示vcl文件的詳細信息,vcl編譯前的樣子
backend.list [<backend_expression>]                #顯示后端服務器列表
backend.set_health <backend_expression> <state>    #手動上線下線后端服務器
ban <field> <operator> <arg> [&& <field> <oper> <arg>]...    #清理緩存中的緩存對象
ban.list                                             #顯示定義的清理緩存規則

varnish的訪問日志

[root@vs1 ~]# varnishlog
[root@vs1 ~]# varnishtop

varnish的統計信息

[root@vs1 ~]# varnishstat

五、vcl配置文件的說明

http://book.varnish-software.com/4.0/chapters/VCL_Basics.html

http://book.varnish-software.com/4.0/_images/simplified_fsm.svg

varnish.jpg

vcl_recv    接收請求
cacheable    判斷是否為可緩存對象
incache        判斷hash后的結果是否存在
vcl_hash    可緩存對象hash計算
vcl_hit    緩存中命中
vcl_miss    緩存中未命中
vcl_fetch    獲取后端內容
vcl_deliver    構建緩存發送
vcl_pipe        客戶端請求的方法不是常見方法時,直接交給后端服務器處理
vcl_pass        不檢查緩存直接從后端服務器取
vcl_error    varnish直接返回錯誤響應

六、vcl配置文件

[root@vs1 ~]# cp /etc/varnish/default.vcl /etc/varnish/test.vcl
[root@vs1 ~]# vim /etc/varnish/test.vcl 
# This is an example VCL file for Varnish.
#
# It does not do anything by default, delegating control to the
# builtin VCL. The builtin VCL is called when there is no explicit
# return statement.
#
# See the VCL chapters in the Users Guide at https://www.varnish-cache.org/docs/
# and http://varnish-cache.org/trac/wiki/VCLExamples for more examples.

# Marker to tell the VCL compiler that this VCL has been adapted to the
# new 4.0 format.
vcl 4.0;

# Default backend definition. Set this to point to your content server.
backend vs2 {    #定義后端主機vs2
    .host = "172.16.24.102";
    .port = "80";
    .probe = {    #對后端主機的test1進行進行健康狀態檢測
        .url = "/test1.html";
        }
}
backend vs3 {
    .host = "172.16.24.104";
    .port = "80";
    .probe = {
        .url = "/test1.html";
        }
}
#import directors;    #加載directors模塊,在負載均衡輪詢時要用到
#sub vcl_init {        #輪詢方式的負載均衡
#    new mycluster = directors.round_robin();
#    mycluster.add_backend(vs2);
#    mycluster.add_backend(vs3);
#}

sub vcl_recv {
    # Happens before we check if we have this in cache already.
    #
    # Typically you clean up the request here, removing cookies you don't need,
    # rewriting the request, etc.
    
    #url中開頭帶有login或者admin的直接從后端主機取結果不緩存
    if (req.url ~ "(?i)^/login" || req.url ~ "(?i)^/admin") {  
        return(pass);
    }

    #url以jpg,png,gif結尾的直接發給vs2,其他的都發給vs3
    if (req.url ~ "(?i)\.(jpg|png|gif)$") {
        set req.backend_hint = vs2;
    } else {
        set req.backend_hint = vs3;
    }


#    set req.backend_hint = mycluster.backend();    #負載均衡集群


#如果客戶端請求為PRI返回405,如果請求的為非GET,HEAD,PUT,POST,TRACE,OPTIONS,DELETE都直接發給后端主機處理
    if (req.method == "PRI") {
        /* We do not support SPDY or HTTP/2.0 */
        return (synth(405));
    }
    if (req.method != "GET" &&
      req.method != "HEAD" &&
      req.method != "PUT" &&
      req.method != "POST" &&
      req.method != "TRACE" &&
      req.method != "OPTIONS" &&
      req.method != "DELETE") {
        /* Non-RFC2616 or CONNECT which is weird. */
        return (pipe);
    }

    if (req.method != "GET" && req.method != "HEAD") {
        /* We only deal with GET and HEAD by default */
        return (pass);
    }
    if (req.http.Authorization || req.http.Cookie) {
        /* Not cacheable by default */
        return (pass);
    }
    return (hash);
}


sub vcl_backend_response {
    # Happens after we have read the response headers from the backend.
    #
    # Here you clean the response headers, removing silly Set-Cookie headers
    # and other mistakes your backend does.
}

sub vcl_deliver {
    # Happens when we have all the pieces we need, and are about to send the
    # response to the client.
    #
    # You can do accounting or modifying the final object here.
    #如果緩存能命中就在返回值中插入HIT,未命中則插入MISS
    if (obj.hits>0) {
        set resp.http.X-Cache = "HIT";
    } else {
        set resp.http.X-Cache = "MISS";
    }
}

[root@vs1 ~]# varnishadm -S /etc/varnish/secret -T 127.0.0.1:6082
vcl.load test2 test.vcl
200        
VCL compiled.
vcl.use test2
200        
VCL 'test2' now active

七、測試

在vs2上上傳一張dog.jpg,在vs3上不上傳任何圖片

blob.png

blob.png

blob.png

blob.png

blob.png

blob.png

原創文章,作者:N17_信風,如若轉載,請注明出處:http://www.www58058.com/18401

(0)
N17_信風N17_信風
上一篇 2016-06-19
下一篇 2016-06-20

相關推薦

  • keepalived+nginx 模型示例

    原理為: 調度器 利用 keepalived 保持高可用性,實現對系統的監控和VIP 的floating NGINX 利用upstream模塊進行調度 關鍵點: keepalived 對NGINX 狀態的監控: //利用配置文件中設定的腳本對調度器的nginx 進程的監控 實驗步驟: 基于上一篇LVS-DR架構來做,具體LVS-DR架構請參考上一篇 先設置主…

    2017-05-13
  • 網絡管理

    說起網絡,大家都不陌生,因為大家天天上網嘛,連路邊老大爺都會聊微信了,但是我們所了解的網絡只是茫茫網絡大海中的一葉扁舟,網絡的范圍其實有很大,里面涉及的東西也非常多,現在讓小編帶你一點一點去了解它吧,相信大家看了之后,會有不一樣的體會呢! 1、 什么是網絡? 網絡是由節點和連線構成,表示諸多對象及其相互聯系。在數學上,網絡是一種圖,一般認為專指加權圖。網絡除…

    2017-09-02
  • 創建CA 和申請證書

    創建CA 和申請證書1生成私有CA的私鑰:(umask 066;openssl genrsa -out /etc/pki/CA/private/cakey.pem 2048)注:CA的私鑰文件必須放在/etc/pki/CA/private/cakey.pem 這個路徑里2創建序列號 ,數據庫文件touch  /etc/pki/CA/index.tx…

    Linux干貨 2017-07-17
  • 關于大型網站技術演進的思考(四):存儲的瓶頸(4)

    原文出處: 夏天的森林    如果數據庫需要進行水平拆分,這其實是一件很開心的事情,因為它代表公司的業務正在迅猛的增長,對于開發人員而言那就是有不盡的項目可以做,雖然會感覺很忙,但是人過的充實,心里也踏實。 數據庫水平拆分簡單說來就是先將原數據庫里的一張表在做垂直拆分出來放置在單獨的數據庫和單獨的表里后更進一步的把本來是一個整體…

    2015-03-11
  • 網絡配置、nmcli

    CentOS 7 網絡屬性配置    rhel6 之前,網絡接口使用連續號碼命名:eth0 、eth1 等, 當增加或刪除網卡時,名稱可能會 發生變化    rhel7 使用基于硬件,設備拓撲和設置類型 命名:    (1) 網卡命名機制    &n…

    Linux干貨 2016-09-23
  • redis + keepalived 雙主模型

    redis + keepalived 雙主模型 架構圖:    1.vip默認綁定在redis主上,由redis主提供服務,redis從為備用節點。(實際上提供服務的只是vip) 2.當redis主掛掉,vip會默認漂移至redis從。由redis從提供服務,redis主已經掛掉。 3.當redis主已經恢復,redis從繼續提供服務和掛…

    Linux干貨 2016-06-23
欧美性久久久久