官方文档:http://varnish-cache.org/trac/wiki/VCLExampleDirector

主机:node1:192.168.10.201系统:RHEL7.0

后端服务器:node2:192.168.10.202 系统:RHEL7.3

            node3:192.168.10.203系统:RHEL7.3

主机设置,yum安装好varnish,启动varnish服务

1、动静分离web1图片,web2 http服务

[root@node1 ~]# vim /etc/varnish/default.vcl

backend webserver1 {

    .host = "192.168.10.202";

    .port = "80";

    .probe = {

               .url ="/test1.html";

             }

}

backend webserver2{

    .host = "192.168.10.203";

    .port = "80";

}

sub vcl_recv {

    if (req.url ~ "(?i)/login" || req.url ~ "(?i)/admin") {

       return (pass);

    }

    if (req.url ~ "(?i)\.(jpg|png|gif)$"){

       set req.backend_hint = webserver1;

    } else {

       set req.backend_hint = webserver2;

    }

    if (req.method == "PRI") {

       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") {

                return (pipe);

    }

    if (req.method != "GET" && req.method != "HEAD") {

       return (pass);

    }

    if (req.http.Authorization || req.http.Cookie) {

       return (pass);

    }

    return (hash);

}

sub vcl_deliver {

    if (obj.hits > 0) {

       set resp.http.X-Cache = "HIT from"+server.ip;

    } else {

       set resp.http.X-Cache = "MISS from"+server.ip;

    }

}

[root@node1 ~]# varnishadm  -S /etc/varnish/secret -T 127.0.0.1:6082

vcl.load test7 default.vcl

200       

VCL compiled.

vcl.use test7

200       

VCL 'test7' now active

后端服务器:yum 安装好nginx,测试页

[root@node2 ~]# for i in {1..10};do echo "Page $i on web1" > /usr/share/nginx/html/test$i.html;done

 [root@node3 ~]# for i in {1..10};do echo "Page $i on web2" > /usr/share/nginx/html/test$i.html;done

浏览器打开:192.168.10.201:6081/1.jpg

blob.png

2、负载均衡

[root@node1 ~]# vim /etc/varnish/default.vcl

添加以下代码:

import directors;

sub vcl_init {

    new mycluster = directors.round_robin();

    mycluster.add_backend(webserver1);

    mycluster.add_backend(webserver2);

}

sub vcl_recv中添加:

set req.backend_hint = mycluster.backend();

把示例1的:

if (req.url ~ "(?i)\.(jpg|png|gif)$"){

       set req.backend_hint = webserver1;

    } else {

       set req.backend_hint = webserver2;

    }

删除或者注释掉

分类: Linux服务

发表评论

电子邮件地址不会被公开。 必填项已用*标注

1 × 1 =