当前位置:首页 > PHP教程 > PHP高级教程

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

在 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.

如上图.目前 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 (周博通) 就不知道了.

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



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!