论坛首页 Java企业应用论坛

Spring3.0的ShallowEtagHeaderFilter,非常好呀

浏览 5384 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
作者 正文
   发表时间:2009-11-05   最后修改:2009-11-05
Spring3.0中的对页面的Etag支持,基于的MD5的生成,非常好,可移植到Spring2.5上

Support for ETags is provided by the servlet filter ShallowEtagHeaderFilter. It is a plain Servlet
Filter, and thus can be used in combination with any web framework. The
ShallowEtagHeaderFilter filter creates so-called shallow ETags (as opposed to deep ETags,
more about that later).The filter caches the content of the rendered JSP (or other content), generates an
MD5 hash over that, and returns that as an ETag header in the response. The next time a client sends a
request for the same resource, it uses that hash as the If-None-Match value. The filter detects this,
renders the view again, and compares the two hashes. If they are equal, a 304 is returned. This filter will
not save processing power, as the view is still rendered. The only thing it saves is bandwidth, as the
rendered response is not sent back over the wire.

<filter>
<filter-name>etagFilter</filter-name>
<filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>etagFilter</filter-name>
<servlet-name>petclinic</servlet-name>
</filter-mapping>




		ShallowEtagResponseWrapper responseWrapper = new ShallowEtagResponseWrapper(response);
		filterChain.doFilter(request, responseWrapper);

		byte[] body = responseWrapper.toByteArray();
		String responseETag = generateETagHeaderValue(body);
		response.setHeader(HEADER_ETAG, responseETag);

		String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
		if (responseETag.equals(requestETag)) {
			if (logger.isTraceEnabled()) {
				logger.trace("ETag [" + responseETag + "] equal to If-None-Match, sending 304");
			}
			response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("ETag [" + responseETag + "] not equal to If-None-Match [" + requestETag +
						"], sending normal response");
			}
			response.setContentLength(body.length);
			FileCopyUtils.copy(body, response.getOutputStream());
		}
	
   发表时间:2009-11-05  
是个能提高性能的好东东
0 请登录后投票
   发表时间:2009-11-06  
SSailYang 写道
是个能提高性能的好东东

不是的,官方的解释是,this filter only saves bandwidth, not server performance.
意思是这个过滤器只能节省带快,而不是服务器性能。
http://static.springsource.org/spring/docs/3.0.0.M2/javadoc-api/org/springframework/web/filter/ShallowEtagHeaderFilter.html
0 请登录后投票
   发表时间:2009-11-06  
看看这个基于资源的HTTP Cache的实现介绍,基本同理,而且还解决了一些问题
0 请登录后投票
   发表时间:2009-11-06  
这是原话
As such, this filter only saves bandwidth, not server performance
0 请登录后投票
   发表时间:2009-11-06  
如果要提高性能,需要服务器端的程序做一些额外处理
比如生成etag,可以根据主要数据的最后修改时间来生成
每次先先只取出最后修改时间进行比较,匹配返回304,否则再取数据
0 请登录后投票
   发表时间:2010-01-20  
要想发挥etag的作用需要自己动手实现
etag的值相当于对http response的md5(计算量相当大啊)
发送etag到浏览器后 下次请求同一个url是会带回到服务器
服务可用新生成的etag与旧etag做比较
如果相同返回304 否则返回新页面
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics