`

HTTP缓存 Last-Modified 服务端实现

阅读更多

 

针对图片资源,根据http协议的缓存机制,进行了服务器更新处理,但遇到了个小问题,一直还没搞清楚的.见代码备注.

 

package com.g3net.servlet;

import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@SuppressWarnings("serial")
public class PicServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if (!Appcontext.isstarted) {
			return;
		}
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("image/png");
		String key = req.getParameter("k");
		
		long ifModifiedTime = req.getDateHeader("if-modified-since");
		/* 打印输出 浏览器 返回的if-modified-since请求头数据,均返回 1388712683000l,而非 1388712683125l ,省略了毫秒级别数据.*/
		System.out.println("ifModifiedSince:" + ifModifiedTime );
		
		long lastModifyTime = PicCahceUtil.getLastModifyTime(key);
		/* 因此这里根据modifytime进行判断时,应省去毫秒级数据再进行对比*/
		if(ifModifiedTime != -1 && ifModifiedTime != 0 && ifModifiedTime/1000 == lastModifyTime/1000){
			resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			return;
		}
		byte[] picdata = PicCahceUtil.getPicData(key);
		if (picdata != null && picdata.length > 1) {
			resp.setStatus(HttpServletResponse.SC_OK);
			/*便于测试,下发的"修改时间"为固定值 1388712683125l */
			resp.addDateHeader("Last-Modified", 1388712683125l);
			resp.setHeader("Cache-Control", "max-age=" + 2);//表示浏览器最大缓存两天,两天内会根据modifytime进行更新处理; 超过两天则强制进行更新 
			resp.addDateHeader("Expires", System.currentTimeMillis() + 1000 * 120);//表示浏览器2分钟内不会再次请求服务器,以减少对服务器压力
			/* 下发返回值 */
			OutputStream out = resp.getOutputStream();
			try {
				out.write(picdata);
				out.flush();
			} catch (Exception e) {
				LogService.writeLog(LoggerNameType.FAILLOG, "下发图片数据出错key:"
						+ key, LogService.ERROR);
			} finally {
				out.close();
			}
			// 指标监控
			Appcontext.dataCollection.addFunctionUsingNum("pic", 1);
		} else {
			resp.sendError(HttpServletResponse.SC_NOT_FOUND);
		}
		
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	public static void main(String[] args) {
		long value = 1388712683100l;
		System.out.println(Long.valueOf(value));
	}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics