`
flex_莫冲
  • 浏览: 1091826 次
  • 性别: 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);
}

分享到:
评论

相关推荐

    Varnish purges 缓存清除 教程.docx

    除了VCL中的配置,你还可以通过连接到Varnish的管理端口(默认为6000或3500)并执行特定的CLI命令来清除缓存。例如,对于Varnish 2.1,你可以使用以下命令: ``` telnet 192.168.1.185 3500 purge.url regex_...

    Varnish网站加速缓存代理

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

    nginx和php和varnish配置

    nginx和php和varnish配置

    Varnish 应用技术指南 V3.0 中文版

    8. Varnish的缓存更新和失效策略:了解如何设置缓存过期时间、如何根据内容变化自动更新缓存,以及如何使用Ban命令手动清除特定缓存项,都是使用Varnish时的关键技能。 9. Varnish在API和微服务架构中的应用:...

    高性能缓存服务器Varnish

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

    Varnish使用实例

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

    varnish+lighttpd配置

    你可以使用`varnishstat`命令查看Varnish的统计信息,以便了解缓存效果和调整策略。同时,监控Lighttpd的日志,确保没有错误发生。 **四、Varnish+Lighttpd的优化** 1. **缓存策略优化**:根据网站内容特点,调整...

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

    第一个函数clearVarnish是一个更通用的函数,它接受三个参数:$ip为Varnish服务器的IP地址,$url是要清除缓存的URL,$host为可选参数,用于指定需要清空缓存的主机名。函数内部通过遍历一个数组,尝试对每一个...

    Varnish网站加速缓存代理1

    Varnish的主要目标是提高网站的响应速度和整体性能,通过缓存网页内容来减少对服务器的直接请求。自2006年发布首个0.9版本以来,Varnish因其高效能、低资源占用和稳定性,已经在许多大型网站上取代了如Squid这样的...

    varnish-3.0.7.tgz 源码安装包

    下面将详细介绍Varnish的原理、功能以及如何安装和使用3.0.7版本。 **Varnish基础概念** Varnish是一个开源的反向代理服务器,它的主要作用是接收HTTP请求,并根据预设的策略缓存网页内容。当后续的请求相同内容时...

    linux-varnish配置

    安装并配置好Varnish后,可以使用以下命令启动和停止服务: ```bash sudo systemctl start varnish sudo systemctl enable varnish sudo systemctl status varnish sudo systemctl stop varnish ``` 四、监控与...

    Varnish权威指南(中文)

    《Varnish权威指南》是一本深度探讨Varnish缓存服务器技术的专业书籍,中文版的出版使得更多国内用户能够无障碍地学习和掌握这一高效的内容分发和加速工具。Varnish作为一个开源的HTTP加速器,它在Web性能优化领域...

    varnish-6.2.0.tgz

    2. 更灵活的缓存策略:提供了更多自定义缓存规则的选项,用户可以通过VCL(Varnish Configuration Language)编写自己的缓存策略,实现对不同内容类型和URL的精细化控制。 3. 改进的API和管理工具:提供更强大的...

    varnish测试报告

    Varnish的配置和使用对于提升网站性能至关重要。 ### 测试报告的目的 这份测试报告的目的是评估Varnish缓存在不同并发量下的性能表现。通过模拟多用户并发访问,观察Varnish缓存对Web服务的响应时间、吞吐量等关键...

    varnish-magento

    5. **与其他缓存的集成**:Varnish可以与Magento的其他缓存机制如Full Page Cache (FPC) 结合使用,以实现最佳性能。 6. **更新和维护**:随着Magento和Varnish版本的更新,需要定期检查并更新配置,以确保兼容性和...

    varnish-4.0.3.tar.gz

    这得益于Varnish的高效内存管理,它使用一种称为“存储桶”的数据结构来高效地存储和检索缓存内容,同时Varnish的事件驱动、异步非阻塞I/O模型使其能处理大量并发连接。 Varnish 4.0.3版本可能包含以下组件: 1. **...

Global site tag (gtag.js) - Google Analytics