易享之家 - 专注共享墨白资源网资源 - 易享之家,墨白资源网是中国作品质量最好的的独立博客之一,2008年成立,关注网络推广、SEO、网络技术、网络活动、自媒体、搜索引擎,易享之家,墨白资源网是一个值得收藏的网站。

http加速器Varnish的vcl配置小记(lnmp环境) | 张戈博客

  • 时间:
  • 浏览:1

在以前的公司曾安装过Varnish,可惜还没摸热就离职了,这次接着倒腾了下Varnish,并搭建成功,特来记录下,以备后用。

一、测试环境

系统版本:CentOS 6.4 x64

WEB环境:Nginx+PHP+MySQL

Varnish:3.0

工作原理:简单的说,在本次测试中,Varnish将来自100的请求转发到后端的nginx100100端口,当匹配到请求是jpg、css、js等静态文件时,以前进入缓存中查找,若未找到则将请求发给后端的nginx避免,并缓存此次请求的文件,若下次再次出显相同请求时(通过哈希校验),将直接从缓存中调用。以前Varnish缓存位于内存当中,因此 读取传输传输速率是硬盘无法移觉的,从而实现了HTTP加速(Ps:本文为单台主机测试)。

二、安装Varnish

以前博客以前写过安装Varnish相关文章,就不赘述了,详情:https://zhang.ge/2044.html

三、修改nginx配置

在安装varnish以前,lnmp环境以前搭建OK,因此 假若把nginx所有的监听端口改成100100即可。

vim 编辑 /usr/local/nginx/conf/nginx.conf 把 listen 100 改成 listen 100100,因此执行:

/usr/local/nginx/sbin/nginx -s reload 重新加载nginx即可,记得使用 netstat -nutlp | grep nginx 查看与非 生效。

四、编写vcl配置

稍微修改了下《Varnish+Nginx 配置—-Varnish》一文中分享的vcl配置:

#vim /usr/local/varnish/etc/vcl.conf

# This is a basic VCL configuration file for varnish.  See the vcl(7)  
# man page for details on VCL syntax and semantics.  
#   
# Default backend definition.  Set this to point to your content  
# server.  
   
backend tgweb {  
     .host = "0.0.0.0";  
     .port = "100";  
     .connect_timeout = 20s;  
     .first_byte_timeout = 20s;  
     .between_bytes_timeout = 20s;  
 }  
  
#允许刷新缓存的规则  
#acl purgeAllow {  
#     不可不才能本机进行刷新  
#     "localhost";  
#}  
   
# Below is a commented-out copy of the default VCL logic.  If you  
# redefine any of these subroutines, the built-in logic will be  
# appended to your code.  
  
sub vcl_recv {  
    #判断请求主机,跳转到相应后端服务器  
    #if(req.http.host ~ "^(.*)(zhang.ge)")  
    #{  
    #    set req.backend=tgweb;  
    #}else{  
    #    error 408 "Hostname not found";   
    #}  
      
    #grace缓存过期仍存放  
    # 若backend是健康的,则仅grace 5s,以前backend不健康,则grace 1m。  
    # 这里,5s的目的是为了提高高并发时的吞吐率;  
    # 1m的目的是,backend挂了以前,还能继续服务一段时间,期望backend挂的从不不要

。。。  
    if (req.backend.healthy) {  
        set req.grace = 5s;  
    } else {  
        set req.grace = 1m;  
    }  
  
    #刷新缓存的避免  
    #if (req.request == "PURGE"){  
    #    if(!client.ip ~ purgeAllow) {  
    #            error 405 "Not allowed.";  
    #    }  
    #    #转到hit以前miss避免  
    #    return (lookup);  
    #}  
  
    #移除因此

特定格式的cookie  
    if (req.url ~ "^(.*)\.(jpg|png|gif|jpeg|flv|bmp|gz|tgz|bz2|tbz|js|css|html|htm)($|\?)" ) {  
         #移除cookie,以便能缓存到varnish  
         unset req.http.cookie;  
    }  
  
   #Accept-Encoding 是浏览器发给服务器,声明浏览器支持的编码类型的  
   #修正客户端的Accept-Encoding头信息  
   #避免个别浏览器发送类似 deflate, gzip  
    if (req.http.Accept-Encoding) {  
        if (req.url ~ "^(.*)\.(jpg|png|gif|jpeg|flv|bmp|gz|tgz|bz2|tbz)($|\?)" ) {  
            remove req.http.Accept-Encoding;  
        }else if (req.http.Accept-Encoding ~ "gzip"){  
            set req.http.Accept-Encoding = "gzip";  
        } else if (req.http.Accept-Encoding ~ "deflate"){  
            set req.http.Accept-Encoding = "deflate";  
        } else if (req.http.Accept-Encoding ~ "sdch"){  
            #chrome新增加的压缩  
            set req.http.Accept-Encoding = "sdch";  
        }else {  
            remove req.http.Accept-Encoding;  
        }  
    }          
    #首次访问增加X-Forwarded-For头信息,方便后端进程池池获取客户端ip  
    if (req.restarts == 0) {  
        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;  
        }  
    }  
  
   if (req.request != "GET" &&  
       req.request != "HEAD" &&  
       req.request != "PUT" &&  
       req.request != "POST" &&  
       req.request != "TRACE" &&  
       req.request != "OPTIONS" &&  
       req.request != "DELETE") {  
       return (pipe);  
   }  
     if (req.request != "GET" && req.request != "HEAD") {  
         /* We only deal with GET and HEAD by default */  
         return (pass);  
     }  
     if (req.http.Authorization) {  
         /* Not cacheable by default */  
         return (pass);  
     }  
     #js,css文件都有

Cookie,不可不才能每次都去后台服务器去取  
     #if (req.http.Cookie) {  
     #    /* Not cacheable by default */  
     #    return (pass);  
     #}  
      
     #以前请求的是动态页面直接转发到后端服务器  
     if (req.url ~ "^(.*)\.(php|jsp|do|aspx|asmx|ashx)($|.*)") {  
          return (pass);  
     }  
     return (lookup);  
 }     
 sub vcl_pipe {  
     # Note that only the first request to the backend will have  
     # X-Forwarded-For set.  If you use X-Forwarded-For and want to  
     # have it set for all requests, make sure to have:  
     # set bereq.http.connection = "close";  
     # here.  It is not set by default as it might break some broken web  
     # applications, like IIS with NTLM authentication.  
     return (pipe);  
 }     
#放过,让其直接去后台服务器请求数据  
sub vcl_pass {  
     return (pass);  
 }     
sub vcl_hash {  
     hash_data(req.url);  
     if (req.http.host) {  
         hash_data(req.http.host);  
     } else {  
         hash_data(server.ip);  
     }  
     #支持压缩的要增加,避免发送给不支持压缩的浏览器压缩的内容  
     if(req.http.Accept-Encoding){  
          hash_data(req.http.Accept-Encoding);  
     }  
     return (hash);  
 }  
   
#缓存服务器lookup查找命中:hit  
 sub vcl_hit {  
     #刷新缓存的请求操作,设置TTL为0,返回避免结果代码  
     #if (req.request == "PURGE") {  
     #     set obj.ttl = 0s;  
     #     error 100 "Purged.";  
     # }    
     #缓存服务器命中后(查找到了)  
     return (deliver);  
 }     
#缓存服务器lookup查找如此


命中:miss  
sub vcl_miss {  
    #刷新缓存的请求操作,  
    #if (req.request == "PURGE") {  
    #    error 404 "Not in cache.";  
    #}    
    #缓存服务器如此


命中(去后台服务器取)  
     return (fetch);  
 }    
#从后台服务器撤销数据后,视情况报告与非

进行缓存  
sub vcl_fetch {  
    #以前请求的是动态页面直接发转发  
    #动态请求回来的,一定要装进前面避免  
    if (req.url ~ "^(.*)\.(php|jsp|do|aspx|asmx|ashx)($|.*)") {  
        set beresp.http.Cache-Control="no-cache, no-store";  
        unset beresp.http.Expires;  
        return (deliver);  
    }    
    # 仅当该请求可不才能缓存时,才设置beresp.grace,若该请求不可不才能被缓存,则不设置beresp.grace  
    if (beresp.ttl > 0s) {  
        set beresp.grace = 1m;  
    }      
     if (beresp.ttl <= 0s ||  
         beresp.http.Set-Cookie ||  
         beresp.http.Vary == "*") {  
            /*  
             * Mark as "Hit-For-Pass" for the next 2 minutes  
             */  
            set beresp.ttl = 120 s;  
            #下次请求时不进行lookup,直接pass  
            return (hit_for_pass);  
     }    
    #设置从后台服务器获得的特定格式文件的缓存TTL  
    if (req.url ~ "^(.*)\.(pdf|xls|ppt|doc|docx|xlsx|pptx|chm|rar|zip)($|\?)")       
    {  
        #移除服务器发送的cookie   
        unset beresp.http.Set-Cookie;  
        #上加缓存时间  
        set beresp.ttl = 100d;  
        return (deliver);  
    }else if(req.url ~ "^(.*)\.(bmp|jpeg|jpg|png|gif|svg|png|ico|txt|css|js|html|htm)($|\?)"){  
        #移除服务器发送的cookie   
        unset beresp.http.Set-Cookie;  
        #上加缓存时间  
        set beresp.ttl = 15d;  
        return (deliver);  
    }else if(req.url ~ "^(.*)\.(mp3|wma|mp4|rmvb|ogg|mov|avi|wmv|mpeg|mpg|dat|3pg|swf|flv|asf)($|\?)"){  
        #移除服务器发送的cookie   
        unset beresp.http.Set-Cookie;  
        #上加缓存时间  
        set beresp.ttl = 100d;  
        return (deliver);  
    }    
    #从后台服务器返回的response信息中,如此


缓存的,不缓存  
    if (beresp.http.Pragma ~"no-cache" || beresp.http.Cache-Control ~"no-cache" || beresp.http.Cache-Control ~"private") {  
            return (deliver);  
    }  
    return (deliver);  
 }     
#缓存服务器发送到客户端前调用  
 sub vcl_deliver {  
    #下面是上加两个Header标识,以判断缓存与非

命中。  
    if (obj.hits > 0) {  
        set resp.http.X-Cache = "HIT from TG.varnish-cache.jjcj.com";  
       #set resp.http.X-Varnish = "HIT from TG.varnish-cache.jjcj.com";  
    } else {  
        set resp.http.X-Cache = "MISS from TG.varnish-cache.jjcj.com";  
       #set resp.http.X-Varnish = "MISS from TG.varnish-cache.jjcj.com";  
    }  
    #上加都有

可不才能的header  
    unset resp.http.Vary;  
    unset resp.http.X-Powered-By;  
    unset resp.http.X-AspNet-Version;  
    return (deliver);  
 }  
   
 sub vcl_error {  
     set obj.http.Content-Type = "text/html; charset=utf-8";  
     set obj.http.Retry-After = "5";  
     synthetic {"  
 <?xml version="1.0" encoding="utf-8"?>  
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
 <html>  
   <head>  
     <title>"} + obj.status + " " + obj.response + {"</title>  
   </head>  
   <body>  
     <h1>Error "} + obj.status + " " + obj.response + {"</h1>  
     <p>"} + obj.response + {"</p>  
     <h3>Guru Meditation:</h3>  
     <p>XID: "} + req.xid + {"</p>  
     <hr>  
     <p>Varnish cache server</p>  
   </body>  
 </html>  
 "};  
     return (deliver);  
 }     
 sub vcl_init {  
    return (ok);  
 }    
 sub vcl_fini {  
    return (ok);  
 }

Ps:该配置文件基本都有 完整篇 说明,根据实际情况报告修改下即可。

五、启动Varnish

执行如下命令启动Varnish:

/usr/local/varnish/sbin/varnishd -f /usr/local/varnish/etc/vcl.conf -s malloc,2048m -T 127.0.0.1:100 -a 0.0.0.0:100

 六、测试效果

测试很简单:

①、打开谷歌浏览器,按下F12进入开发者模式,并点击切换到network界面,如图:

②、在地址栏输入测试服务器的ip,并打开,可不才能想看 network上边以前出显页面相关文件的信息:

③、在列表中找到并点击两个静态文件,比如jpg或js文件,想看 Varnish信息则为搭建成功:

从图中可不才能看出,此时还是MISS情况报告,说明这是第一次打开,还未进行缓存。

④、按下F5刷新页面后,再次点击你是什么 静态文件,可不才能想看 该文件以前是HIT命中情况报告了,说明文件缓存成功:

⑤、继续查看其它静态文件,比如jpg、css、png等文件,均可不才能发现以前是HIT情况报告了。

七、写在最后

从测试可不才能看出,Varnish适合静态文件比较多,而WEB服务器IO又位于严重瓶颈时的加速。本文为单台主机的简单测试,并未深入研究varnish的因此 功能配置,希望可不才能给初次接触Varnish搭建的童鞋提供因此 帮助。