varnish-安装使用-干货

varnish 安装使用


以centos为例安装varnish4

具体可以参考官方链接 https://www.varnish-cache.org/installation/redhat

# 安装varnish repo
rpm --nosignature -i https://repo.varnish-cache.org/redhat/varnish-4.0.el6.rpm
# 安装varnish
yum install varnish

由于墙的原因,如果不能安装varnish repo,可以直接通过翻墙下载varnish的rpm来直接安装varnish (我是直接使用的红杏chrome插件一个月10块,挺不错,我不是托儿)

rpm地址:http://repo.varnish-cache.org/redhat/varnish-4.0/el6/x86_64/varnish/

varnish-libs-devel-4.0.3-1.el6.x86_64.rpm
varnish-libs-4.0.3-1.el6.x86_64.rpm
varnish-docs-4.0.3-1.el6.x86_64.rpm
varnish-debuginfo-4.0.3-1.el6.x86_64.rpm
varnish-4.0.3-1.el6.x86_64.rpm

具体包的作用可以通过名字来反映出,注意安装顺序。

相关文件:

/etc/varnish/               vcl配置文件默认目录。
/etc/sysconfig/varnish      varnish配置文件
/etc/sysconfig/varnishncsa  varnish ncsa日志配置文件
/var/log/varnish/           默认varnish日志存放目录
/etc/init.d/varnish         varnish启动脚本
/etc/init.d/varnishlog      varnish debug日志启动脚本
/etc/init.d/varnishncsa     varnish ncsa日志启动脚本

可用命令:

varnishadm          varnish管理接口CLI
varnishd            varnish daemon
varnishhist         varnish柱状显示图程序 
varnishlog          varnish debug日志命令
varnishncsa         varnish ncsa日志命令
varnish_reload_vcl  varnish reload vcl命令
varnishstat         varnish状态查看命令
varnishtest         测试varnish程序的命令
varnishtop          varnish 日志排名

具体每个命令的解释,如果安装了varnish-docs-4.0.3-1.el6.x86_64.rpm 都可以通过man来查看,建议安装。

配置varnish

关于varnish的配置主要两个

/etc/sysconfig/varnish      关于varnishd运行参数的配置
/etc/varnish/default.vcl    vcl配置文件,如何处理http请求

varnish启动脚本调用/etc/sysconfig/varnish,每项参数在该配置文件中均有说明

vim /etc/sysconfig/varnish

# Configuration file for varnish
#
# /etc/init.d/varnish expects the variable $DAEMON_OPTS to be set from this
# shell script fragment.
#

# Maximum number of open files (for ulimit -n)
NFILES=131072
# 如果ulimit -n的值小于NFILES ,以内核参数为准,如果大于,以NFILES为准

# Locked shared memory (for ulimit -l)
# Default log size is 82MB + header
MEMLOCK=82000

# Maximum number of threads (for ulimit -u)
NPROCS="unlimited"

# Maximum size of corefile (for ulimit -c). Default in Fedora is 0
# DAEMON_COREFILE_LIMIT="unlimited"

# Set this to 1 to make init script reload try to switch vcl without restart.
# To make this work, you need to set the following variables
# explicit: VARNISH_VCL_CONF, VARNISH_ADMIN_LISTEN_ADDRESS,
# VARNISH_ADMIN_LISTEN_PORT, VARNISH_SECRET_FILE, or in short,
# use Alternative 3, Advanced configuration, below
RELOAD_VCL=1
# 值为1时,可以通过调用/etc/init.d/varnish reload来重载vcl。

# This file contains 4 alternatives, please use only one.

## Alternative 1, Minimal configuration, no VCL
#
# Listen on port 6081, administration on localhost:6082, and forward to
# content server on localhost:8080.  Use a fixed-size cache file.
#
#DAEMON_OPTS="-a :6081 \
#             -T localhost:6082 \
#             -b localhost:8080 \
#             -u varnish -g varnish \
#             -s file,/var/lib/varnish/varnish_storage.bin,1G"


## Alternative 2, Configuration with VCL
#
# Listen on port 6081, administration on localhost:6082, and forward to
# one content server selected by the vcl file, based on the request.  Use a
# fixed-size cache file.
#
#DAEMON_OPTS="-a :6081 \
#             -T localhost:6082 \
#             -f /etc/varnish/default.vcl \
#             -u varnish -g varnish \
#             -S /etc/varnish/secret \
#             -s file,/var/lib/varnish/varnish_storage.bin,1G"


## Alternative 3, Advanced configuration
#
# See varnishd(1) for more information.
#
# # 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=
# 监听地址,如果没有指定,将监听在所有接口上
VARNISH_LISTEN_PORT=80
# 监听端口

#
# # Telnet admin interface listen address and port
VARNISH_ADMIN_LISTEN_ADDRESS=192.168.11.208
VARNISH_ADMIN_LISTEN_PORT=6082
# 管理监听地址和端口

#
# # Shared secret file for admin interface
VARNISH_SECRET_FILE=/etc/varnish/secret
#
# # The minimum number of worker threads to start
VARNISH_MIN_THREADS=50
# 伴随varnishd启动是每个work启动的线程数量,如果大量请求,请将此值调大,以避免启动后的短暂瞬间线程数量不够导致的链接丢失。

#
# # The Maximum number of worker threads to start
VARNISH_MAX_THREADS=1000
# 最大work启动线程数量,
#
# # Idle timeout for worker threads
VARNISH_THREAD_TIMEOUT=120
# 如果threads在120秒处于空闲状态,将会被varnish回收掉,但最终threads的值也不会小于VARNISH_MIN_THREADS定义值

#
# # Cache file size: in bytes, optionally using k / M / G / T suffix,
# # or in percentage of available disk space using the % suffix.
VARNISH_STORAGE_SIZE=500M
# 指定varnishd用来存放cache的空间。

#
# # Backend storage specification
VARNISH_STORAGE="malloc,${VARNISH_STORAGE_SIZE}"
# 指定varnish的存储类型,可选file、malloc
#
# # Default TTL used when the backend does not specify one
VARNISH_TTL=120
#
# # DAEMON_OPTS is used by the init script.  If you add or remove options, make
# # sure you update this section, too.
DAEMON_OPTS="-a ${VARNISH_LISTEN_ADDRESS}:${VARNISH_LISTEN_PORT} \
            -f ${VARNISH_VCL_CONF} \
            -T ${VARNISH_ADMIN_LISTEN_ADDRESS}:${VARNISH_ADMIN_LISTEN_PORT} \
            -t ${VARNISH_TTL} \
            -p thread_pool_min=${VARNISH_MIN_THREADS} \
            -p thread_pool_max=${VARNISH_MAX_THREADS} \
            -p thread_pool_timeout=${VARNISH_THREAD_TIMEOUT} \
            -u varnish -g varnish \
            -S ${VARNISH_SECRET_FILE} \
            -s ${VARNISH_STORAGE}"
# 将上面的变量引用到DAEMON_OPTS参数,varnishd启动时会应用DAEMON_OPTS
#


## Alternative 4, Do It Yourself. See varnishd(1) for more information.
#
# DAEMON_OPTS=""

vim /etc/varnish/default.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.
# 指定从哪里可以取得资源。这样一个简单的vanish配置就完成了
backend default {
    .host = "192.168.11.208";
    .port = "81";
}

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.
}

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.
    if (bereq.url ~ "\.(js|css|png|jpg|ico)$" && beresp.ttl <= 1200s && beresp.status == 200) {
        unset beresp.http.set-cookie;
        unset beresp.http.Cache-Control;
        unset beresp.http.Via;
        set beresp.ttl = 1200s;
    }
}

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.
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT from varnish "+obj.hits;
    } 
    else {
        set resp.http.X-Cache = "MISS from varnish "+obj.hits;
    }
    return (deliver);
}

启动varnish

/etc/init.d/varnish start

这时通过访问你的网页,js/css/png/jpg/ico的资源将会被缓存,如果你需要缓存其他资源可以在vclbackendresponse中定义,ttl指定缓存的时间,如果不指定默认读取/etc/sysconfig/varnish中的TTL的值120秒。

通过查看http的响应头将发现

Accept-Ranges:bytes
Age:73
Connection:keep-alive
Content-Length:2040
Content-Type:text/css
Date:Fri, 05 Jun 2015 08:35:36 GMT
ETag:"55715980-7f8"
Last-Modified:Fri, 05 Jun 2015 08:10:40 GMT
Server:openresty
Via:1.1 varnish-v4
X-Cache:HIT from varnish 496
X-Varnish:30314557 10948617

特别注意的是:在某些条件下varnish将不缓存内容,最常见的是使用cookie。当一个被标记有cookie的客户端web请求,varnish默认是不缓存。这些众多的varnish功能特点都是可以通过写vcl来改变的。

sub vcl_recv {
        # Remove the cookie header to enable caching
        unset req.http.cookie;
}

最后提个建议,如果要使用varnish缓存html,这时你需要考虑的是,是否包含cookie,已经后台的更新(包括评论管理,文章修改,屏蔽等等)如何通知varnish等等,需要你结合你的应用来添加vcl配置参数。典型的便是在发起后台更新操作时在vcl配置文件中截获文章的id,然后更新缓存。

提供一个参考例子:

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.
    # html先清除cookie
    if (req.method == "GET" && req.url ~ "^/articles/.*\.html$" && req.http.referer !~ "console" ) {
        unset req.http.Cookie;
        unset req.http.Cache-Control;
        return(hash);
    }

    # 评论更新
    if (req.method == "POST" && req.url ~ "/reviews"  ) {
        set req.http.purge-url = regsub(req.http.referer,"http://www.example.com.cn/articles/","");
        ban("req.url ~ " + req.http.purge-url);
        set req.backend_hint = default;
        return(pass);
    }

    # 文章更新
    if (req.method == "POST" && req.url ~ "/console/articles/\d+" ) {
        set req.http.purge-url = regsub(req.url,"/console/articles/(\d+).*","\1");
        ban("req.url ~ " + req.http.purge-url + ".html$");
        set req.backend_hint = default;
        return(pass);
    }

    # 为发往后端主机的请求添加X-Forward-For首部
    if (req.http.X-Forward-For) {    
        set req.http.X-Forward-For = req.http.X-Forward-For + "," + client.ip;
    } else {
        set req.http.X-Forward-For = client.ip;
    }

    if (req.http.host ~ "static.example.com.cn") {
        set req.backend_hint = static;
        return (hash);
    } elsif (req.http.host ~ "image(\d)*.example.com.cn") {
        set req.backend_hint = image;
        return (hash);
    } elsif (req.http.host ~ "www.example.com.cn" && req.url ~ "\.(png|jpg)$") {
        set req.backend_hint = default;
        return(hash);
    } else {
        set req.backend_hint = default;
    }

}

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

    if (bereq.url ~ "\.(html)$" && beresp.ttl <= 600s && beresp.status == 200 &&  beresp.http.set-cookie !~ "staff_id") {
        unset beresp.http.set-cookie;
        unset beresp.http.Cache-Control;
        unset beresp.http.Via;
        set beresp.ttl = 600s;
    }

    if (bereq.url ~ "\.(js|css|png|jpg|ico)$" && beresp.ttl <= 1200s && beresp.status == 200) {
        unset beresp.http.set-cookie;
        unset beresp.http.Cache-Control;
        unset beresp.http.Via;
        set beresp.ttl = 1200s;
    }
}


转载于:https://my.oschina.net/monkeyzhu/blog/425391

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值