当前位置: 首页 > 图文教程 > 网络编程 > PHP > Http 1.1 Etag 与 Last-Modified提高php效率

PHP
php 清除网页病毒的方法
php 远程关机操作的代码
Zend Studio for Eclipse的java.lang.NullPointerException错误的解决方法
PHP 出现乱码和Sessions验证问题的解决方法!
php2html php生成静态页函数
中英文字符串翻转函数
php escape URL编码
PHP Google的translate API代码
php 文件状态缓存带来的问题
linux下 C语言对 php 扩展
php mssql 数据库分页SQL语句
php IP及IP段进行访问限制的代码
PHP 采集程序 常用函数
php 设计模式之 单例模式
php 设计模式之 工厂模式
php xml-rpc远程调用
php 获取完整url地址
PHP MSSQL 存储过程的方法
PDP Document 代码注释规范
PHP HTML代码串截取代码

PHP 中的 Http 1.1 Etag 与 Last-Modified提高php效率


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 290 ::
收藏到网摘: n/a

在 Blog 盛行的今天,一些 Web 应用需要解析大量的 RSS Feed .如何提高效率是个非常重要的问题.在 MagpieRSS 的 Features 中列举了这样的一条: HTTP Conditional GETs Save bandwidth and speed up download times with intelligent use of Last-Modified and ETag.. 这里的 Etag 引起了我的注意.

什么是 Etag ?

通过阅读 RFC 2616 ,得到了对 Etag 的一点印象:

The ETag response-header field provides the current value of the entity tag for the requested variant......Entity tags are normally "strong validators," but the protocol provides a mechanism to tag an entity tag as "weak." One can think of a strong validator as one that changes whenever the bits of an entity changes, while a weak value changes whenever the meaning of an entity changes. Alternatively, one can think of a strong validator as part of an identifier for a specific entity, while a weak validator is part of an identifier for a set of semantically equivalent entities.

从上我们可以大致得知,Entity tags 本质上说是一种"强校验器",但是 HTTP 协议提供了一种通过给 Entity tags 打标签的"弱"的机制(类似于内容的校验码).虽然这段话后面通过两种方式进行了解释,但是还是有些晦涩.我看了这段话之后只是得出了 Etag 的 "E" 代表 "Entity" 而已.

Magpie 首页上提到了一篇文章: HTTP Conditional Get for RSS Hackers ,拜读之后清晰了许多.要先说说 HTTP Conditional GETs 的基本原理,很简单,就是说,从 Web 服务器取数据的时候,如果文件变化了,给我新的文件,如果文件没有变化,只需告诉客户端没有变化即可,不必再把文件取回来.这样就可节省大量的网络带宽和资源.

Etag 与 Last-Modified 是从 HTTP 1.0 到 HTTP 1.1 才有的概念.当我们从 Web 服务器获取文件的时候,只需要读取 HTTP 响应头的 Etag 与 Last-Modified 字段即可,这两个字段里面的具体内容是什么可以不管(可能会千奇百怪,RFC 2616 对 Etag 没有具体值的定义),把这两个值 Cache 在本地,下次检查文件是否更新的时候比对这两个值即可.如果没有变化,服务器的响应代码不是 HTTP 200 (OK) , 而是 304.

http.304.png

如上图.目前 OpenRSS 虽然订阅了40 多个 Feed,但是响应速度很不错.在使用 Gregarius 的过程中(Lilina 也应用了 ETag),发现了 FeedBurnrer 烧录的 Feed ,几乎都是用了 Etag 的(否则估计服务器要瘫痪,Hoho).我们再测试一下 HTTP header 的响应情况:

$ curl -I http://feeds.feedburner.com/dbanotes
HTTP/1.1 200 OK
Date: Tue, 25 Oct 2005 11:34:15 GMT
Server: Apache
Last-Modified: Tue, 25 Oct 2005 04:30:12 GMT
ETag: U4q478bDKLqZ8UMMC8A5afZuHug
Content-Type: text/xml;charset=utf-8
$ curl -I http://feeds.feedburner.com/dbanotes
HTTP/1.1 200 OK
Date: Tue, 25 Oct 2005 11:34:21 GMT
Server: Apache
Last-Modified: Tue, 25 Oct 2005 04:30:12 GMT 
ETag: U4q478bDKLqZ8UMMC8A5afZuHug
Content-Type: text/xml;charset=utf-8

在这个期间,我的 Blog 没有更新.所以 Last-Modified 和 ETag 返回的都是相同的值.这样 Gregarius 就不必重新解析了. 国内的 GreatNews 是支持 HTTP Conditional GETs 的,更棒的是还支持 gzip/deflate encoding.而另一个 RSS 阅读工具 POPU (周博通) 就不知道了.

以上是我的笔记,如有理解错误,请指正!