varnish 4.0 相关注意


varnish 4.0 相关注意_第1张图片



一个线上实例:

vcl 4.0;
backend default {
    .host = "10.171.199.83";
    .port = "81";
}
backend image {
    .host = "10.171.199.83";
    .port = "81";
}
backend static {
    .host = "10.171.199.83";
    .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.
    if (req.method == "GET" && req.url ~ "^/articles" ) {
        unset req.http.cookie;
        unset req.http.Cookie;
        unset req.http.Cache-Control;
    }
    
    if (req.http.X-Forward-For) {    # 为发往后端主机的请求添加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.nbd.com.cn") {
        set req.backend_hint = static;
        return (hash);
    } 
    elsif (req.http.host ~ "image(\d)*.nbd.com.cn") {
        set req.backend_hint = image;
        return (hash);
    } 
    else {
        set req.backend_hint = default; #除开image\d 和static域名的直接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 <= 120s) {
        unset beresp.http.set-cookie;
        unset beresp.http.Cache-Control;
     set beresp.ttl = 120s;
  }
}
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.
    #set resp.http.x-hits = obj.hits;
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT from cache"+obj.hits;
    } 
    else {
        set resp.http.X-Cache = "MISS from cache"+obj.hits;
    }
    return (deliver);
}



为什么varnish将所有的请求都发到后端服务器去了?

         通常是两个问题导致的:

                 1、 目标的TTL过短。通常的解决方式是后端服务器不设置TTL,使用varnish默认的TTL。(默认是120s)

                 2、 你使用了cookies:

默认情况下,varnish不会缓存backend返回的带cookie的结果。

默认情况下,varnish不对包含cookie的请求服务,直接pass他们到后端服务器。


你可能感兴趣的:(varnish 4.0 相关注意)