`
flex_莫冲
  • 浏览: 1075208 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

varnish的使用和PHP清除缓存的技巧

    博客分类:
  • php
阅读更多
官網地址
https://www.varnish-cache.org
安裝路徑
On Debian/Ubuntu this is /etc/default/varnish

設置Backend servers
/etc/varnish/default.vcl

vcl 4.0;

import directors;

# Default backend definition. Set this to point to your content server.
backend default{
    .host = "192.168.2.3";
    .port = "80";
    .connect_timeout = 600s;
    .first_byte_timeout = 600s;
    .between_bytes_timeout = 600s;
    .max_connections = 800;
}

admin  console
varnishadm

varnish是緩存在內存的,查看log
varnishlog
varnishlog -g raw
varnishtop -i BereqURL  # will show you what your backend is being asked the most.
varnishtop -i ReqURL #will show you what URLs are being asked for by the client
varnishtop -I ReqHeader #Accept-Encoding will show the most popular Accept-Encoding header the client are sending you.

varnishstat  #統計


查看版本
varnishd -V

停止
service varnish stop

重启
service varnish restart

特别注意:如果修改了vcl文件,必须重启才会生效

Purging and banning
https://www.varnish-cache.org/docs/4.1/users-guide/purging.html
在default.vcl配置文件中設置允許執行purging操作的ip段,下面表示本機和2.0~2.24的IP都可以執行
# Only allow purging from specific IPs
acl purge {
    "localhost";
    "127.0.0.1";
    "192.168.2.0"/24;
}

# This function is used when a request is send by a HTTP client (Browser)
sub vcl_recv {
call detect_device;
# Normalize the header, remove the port (in case you're testing this on various TCP ports)
# set req.http.Host = regsub(req.http.host, ":[0-9]+", "");
# if (req.http.Host == "*.example.com") {
#set req.backend_hint = test.backend();
# }


# Allow purging from ACL
if (req.method == "PURGE") {
# If not allowed then a error 405 is returned
if (!client.ip ~ purge) {
return(synth(405, "This IP is not allowed to send PURGE requests."));
}

#ban("req.http.host == " + req.http.host + " && req.url == " + req.url);
ban("req.http.host == " + req.http.host + " && req.url ~ " + req.url);

# Throw a synthetic page so the
# request won't go to the backend.
return(synth(200, "Ban added"));
}

# Post requests will not be cached
if (req.http.Authorization || req.method == "POST") {
return (pass);
}

# --- Wordpress specific configuration

# Did not cache the RSS feed
if (req.url ~ "/feed") {
return (pass);
}

# Blitz hack
        if (req.url ~ "/mu-.*") {
                return (pass);
        }


# Did not cache the admin and login pages
if (req.url ~ "/wp-(login|admin)") {
return (pass);
}

# Do not cache the WooCommerce pages
### REMOVE IT IF YOU DO NOT USE WOOCOMMERCE ###
#if (req.url ~ "/(cart|my-account|checkout|addons|/?add-to-cart=)") {
        # return (pass);
    #}

# Remove the "has_js" cookie
set req.http.Cookie = regsuball(req.http.Cookie, "has_js=[^;]+(; )?", "");

# Remove any Google Analytics based cookies
set req.http.Cookie = regsuball(req.http.Cookie, "__utm.=[^;]+(; )?", "");

# Remove the Quant Capital cookies (added by some plugin, all __qca)
set req.http.Cookie = regsuball(req.http.Cookie, "__qc.=[^;]+(; )?", "");

# Remove the wp-settings-1 cookie
set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-1=[^;]+(; )?", "");

# Remove the wp-settings-time-1 cookie
set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-time-1=[^;]+(; )?", "");

# Remove the wp test cookie
set req.http.Cookie = regsuball(req.http.Cookie, "wordpress_test_cookie=[^;]+(; )?", "");

# Are there cookies left with only spaces or that are empty?
if (req.http.cookie ~ "^ *$") {
    unset req.http.cookie;
}

# Cache the following files extensions
if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico)") {
unset req.http.cookie;
}

# Normalize Accept-Encoding header and compression
# https://www.varnish-cache.org/docs/3.0/tutorial/vary.html
if (req.http.Accept-Encoding) {
# Do no compress compressed files...
if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)$") {
   unset req.http.Accept-Encoding;
} elsif (req.http.Accept-Encoding ~ "gzip") {
    set req.http.Accept-Encoding = "gzip";
} elsif (req.http.Accept-Encoding ~ "deflate") {
    set req.http.Accept-Encoding = "deflate";
} else {
unset req.http.Accept-Encoding;
}
}

# Check the cookies for wordpress-specific items
if (req.http.Cookie ~ "wordpress_" || req.http.Cookie ~ "comment_") {
return (pass);
}
if (!req.http.cookie) {
unset req.http.cookie;
}

# --- End of Wordpress specific configuration

# Did not cache HTTP authentication and HTTP Cookie
#if (req.http.Authorization || req.http.Cookie) {
if (req.http.Authorization) {
# Not cacheable by default
return (pass);
}

# Cache all others requests
return (hash);
}


怎麼判別頁面是varnish生成的?
window在host中添加varnish ip 匹配网站domain,例如
192.168.xx.xx xxx.com

打開website,在console中選擇netword,如果請求項的header中有age說明用了varnish
可以設置多個hos,可以用ip也可以用domain。如果varnish重启了或者purge了缓存,则age会变成0

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}
We add a new backend.:

backend java {
    .host = "127.0.0.1";
    .port = "8000";
}

backend server1 {
    .host = "server1.example.com";
    .probe = {
        .url = "/";
        .timeout = 1s;
        .interval = 5s;
        .window = 5;
        .threshold = 3;
    }
}

backend server2 {
    .host = "server2.example.com";
    .probe = {
        .url = "/";
        .timeout = 1s;
        .interval = 5s;
        .window = 5;
        .threshold = 3;
    }
}

sub vcl_init {
    new bar = directors.round_robin();
    bar.add_backend(server1);
    bar.add_backend(server2);
}

--------------
vcl 的正則表達式的寫法
https://gist.github.com/dimsemenov/10100415
http://book.varnish-software.com/3.0/VCL_Basics.html
http://www.hostingadvice.com/how-to/varnish-regex/

-----------------
怎么用PHP删除varnish 指定host或某个url的cache?
/**
 * @param url string e.g:/Vip/detail?id=99
 * @param path string e.g:/Vip/detail
 * @param params array,e.g:{id:99}
 */
public function purgeCache($url = "", $path = "", $params = "") {
	$varnishHost = C("VARNISH_SERVER");
	$regxUrl = "";
	if ($url) {
		$varnishHost. = $url;
	}
	elseif($path) {
		$regxUrl = "^".$path;
		if (!empty($params)) {
			$regxUrl. = "(/?)(.*)?";
			$regxParams = array();
			foreach($params as $key =  > $value) {
				$regxParams[] = "($key=$value|/$key/$value)";
			}
			$regxUrl. = implode("", $regxParams);
		}
		$regxUrl. = ".*$";
	}
	//$url = "^/Vip/detail(/?)(\?id=99|/id/99)$";
	//^/Finance/detail(/?)(.*)?(id=4178|/id/4178).*$
	$method = "PURGE";
	$hosts = C("VARNISH_HOSTS");
	foreach($hosts as $key =  > $frontHost) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
		curl_setopt($ch, CURLOPT_URL, $varnishHost);
		$headers = array();
		$headers[] = 'Connection: Keep-Alive';
		$headers[] = "Host: ".$frontHost;
		if ($regxUrl) {
			$headers[] = "X-Purge-Regex: $regxUrl";
			echo "use regex<br>";
		}
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_REFERER, $frontHost);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$data = curl_exec($ch);
		//dump($data);
		$curlErrorCode = curl_errno($ch);
		if ($curlErrorCode) {
			//echo "purge varnish cache failed.Curl error: " . curl_error($ch);
			Log::write("purge varnish cache failed.Curl error: ".curl_error($ch));
		}
		curl_close($ch);
	}

	return true;
}



为什么要使用X-Purge-Regex?
因为vcl中的req.url获取的是curl的url的path,而这个path是不能传递正则表达式的,因此放到header中,自定义个属性来判断。

使用这个function

public function purgeTest() {
	$url = "";
	$path = "/Article/detail";
	$params = array("id"=>4178);
	$this->purgeCache($url, $path, $params);
}

分享到:
评论

相关推荐

    nginx和php和varnish配置

    nginx和php和varnish配置

    Varnish purges 缓存清除 教程.docx

    Varnish purges 缓存清除 教程.docx

    Varnish网站加速缓存代理

    一款高性能的开源HTTP加速器,2006年发布的第一个版本0.9,发展到...挪威最大的在线报纸 Verdens Gang 使用3台Varnish代替了原来的12台Squid,性能比以前更好。 2.作者:Poul-Henning Kamp是FreeBSD的内核开发者之一。

    高性能缓存服务器Varnish

    Varnish是一款高性能、开源的反向代理服务器和缓存服务器,其开发者Poul-Henning Kamp是FreeBSD核心的开发人员之一。Varnish采用全新的软件体系结构,和现在的硬件体系配合比较紧密。

    Varnish使用实例

    本书是介绍如何快速使用Varnish的一本电子书,英文的

    varnish——图形化清理缓存

    步骤一:从真机给server1代理传一个压缩包 bansys 步骤二:在server1代理服务器上面进行设置 ...域名改为www.westos.org(对这个域名的数据进行缓存清理) vim /etc/httpd/conf/httpd.conf apahce端口为8080 systemctl

    Varnish配置教程和学习资料合集

    教程名称: Varnish配置教程和学习资料合集【】HTTP加速器varnish安装部署【】varnish cache 配置使用ChinaUnix【】varnish 原理【】Varnish-vcl的配置【】varnish配置实例 资源太大,传百度网盘了,链接在附件中,...

    Varnish 2.1.2 安装与配置

    Varnish 2.1.2 缓存负载,做反向代理缓存优于squid

    解析Linux下Varnish缓存的配置优化

    Varnish是一款高性能的开源HTTP加速器,挪威最大的在线报纸 Verdens Gang 使用3台Varnish代替了原来的12台Squid,性能比以前更好。...通过Varnish管理端口,可以使用正则表达式快速、批量地清除部分缓存,这一点是Squi

    laravel-varnish, 使 varnish 和 Laravel 在一起很好.zip

    laravel-varnish, 使 varnish 和 Laravel 在一起很好 使 varnish 和 Laravel 在一起很好 这个包提供了一个简单的方法,可以在 Laravel 中使用 varnish 4 ( 或者 5 ) 。 它提供了路由中间件,在应用到路由时,将确保 ...

    varnish-6.1.1.tgz

    由于varnish先进的设计理念,性能要比squid高上许多,varnish还可以通过端口进行管理,使用正则语句做到清除指定缓存的功能,这些squid都做不到。但是varnish在高并发的情况下,资源消耗较高,而且varnish服务进程...

    varnish-4.1.11.tgz

    由于varnish先进的设计理念,性能要比squid高上许多,varnish还可以通过端口进行管理,使用正则语句做到清除指定缓存的功能,这些squid都做不到。但是varnish在高并发的情况下,资源消耗较高,而且varnish服务进程...

    varnish安装包

    varnish 安装包 varnish 安装包 varnish 安装包 varnish 安装包

    linux-varnish配置

    linux-varnish配置

    varnish缓存配置及其使用.doc

    • 如果不提供命令行选项 (-b hostname:port ),则 backend default 部分将指定要连接的服务器。 • 当守护进程收到一个客户机请求时,将调用 vcl...lookup 将尝试在缓存中查找响应,而 insert 将把响应添加到缓存中。

    varnish+lighttpd配置

    varnish+lighttpd配置

    varnish测试报告

    varnish测试报告

    PHP 清空varnish 缓存的详解(包括指定站点下的)

    本篇文章是对清空varnish的缓存(包括指定站点下的)进行了详细的分析介绍,需要的朋友参考下

    Asp.NET性能优化之反向代理缓存 varnish

    我们讨论了把缓存存放在ASP.NET的输出缓存中(内存和硬盘),以及浏览器缓存中,而大型站点的另一种常用做法是将缓存部署在反向代理服务器上,这类缓存我们通常称之为反向代理缓存,比如Squid和Varnish。这两款软件...

    varnish 官方白皮书文档

    varnish 官方白皮书文档,包含配置信息,说明信息,方便查阅使用。

Global site tag (gtag.js) - Google Analytics