服务端的控制这里只是简单的写了个示列,展示怎么使用,在项目开发中需要根据实际情况进行控制。下面展现所使用到的代码:
CacheServlet

/**
 * Servlet implementation class CacheServlet
 */
@WebServlet("/CacheServlet")
public class CacheServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public CacheServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        //
         testData(request,response);
//      testFile(request, response);

    }

    public void testData(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String rspData = "{useid:34203284394}";
        String etag = EtagUtil.getMd5Digest(rspData);
        if(CacheUtil.isCacheModify(etag, request, response)){
            // 设置缓存时间为60秒
            long cacheTime = 60l;
            CacheUtil.setCacheTimesByCacheControl(cacheTime, response);
            response.getWriter().write(rspData);
        }
    }

    // 文件测试
    public void testFile(HttpServletRequest request, HttpServletResponse response) {
        File f = new File("D:\\images\\icon_unit.png");
        if (CacheUtil.isCacheModify(CacheUtil.changeTimeToSecond(f.lastModified()), request, response)) {
            CacheUtil.setCacheTimesByCacheControl(60l, response);
            writeFileToClient(response, f);
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }


    /**
     * 向客户端写文件
     * 
     * @param response
     * @param file
     */
    private void writeFileToClient(HttpServletResponse response, File file) {
        response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
        response.setContentType("application/octet-stream");
        response.setContentLength(Integer.valueOf(String.valueOf(file.length())));
        FileInputStream fis = null;
        OutputStream os = null;
        ByteArrayOutputStream bos = null;
        try {
            fis = new FileInputStream(file);
            os = response.getOutputStream();
            bos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len = -1;
            while ((len = fis.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                bos.writeTo(os);
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

}

CacheUtil

/**
 * @author ruby
 * @version 1.0
 * @since
 */
public class CacheUtil {
    /**
     * 检测缓存是否发生改变
     * 
     * @param lastModifyTimes上次修改时间单位秒
     * @param request
     * @param response
     * @return false:缓存未发生变化,设置Status为304;true缓存发生变化,设置Status为200
     */
    public static boolean isCacheModify(long lastModifyTime, HttpServletRequest request, HttpServletResponse response) {
        long cacheHeaderTimes = request.getDateHeader("If-Modified-Since");
        lastModifyTime = lastModifyTime * 1000;
        // 缓存发生改变
        if (lastModifyTime != cacheHeaderTimes) {
            response.setStatus(HttpServletResponse.SC_OK);
            response.addDateHeader("Last-Modified", lastModifyTime);
            return true;
        } else {// 未改变
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return false;
        }
    }

    /**
     * 根据ETag值检测缓存是否发生改变
     * 
     * @param etag数据标识
     * @param request
     * @param response
     * @return false:缓存未发生变化,设置值304;true缓存发生变化,设置200
     */
    public static boolean isCacheModify(String etag, HttpServletRequest request, HttpServletResponse response) {
        String cacheHearetag = request.getHeader("If-None-Match");
        // 缓存发生改变
        if (!etag.equals(cacheHearetag)) {
            response.setStatus(HttpServletResponse.SC_OK);
            response.addHeader("ETag", etag);
            return true;
        } else {// 未改变
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return false;
        }
    }

    /**
     * 通过Cache-Control方式设置缓存有效期 缓存多久失效
     * 
     * @param cacheTimes单位秒
     * @param response
     */
    public static void setCacheTimesByCacheControl(long cacheTime, HttpServletResponse response) {
        response.addHeader("Cache-Control", "max-age=" + String.valueOf(cacheTime));
    }

    /**
     * 通过Expires方式设置缓存有效期 到达指定日期后缓存失效
     * 
     * @param cacheTimes单位秒
     * @param response
     */
    public static void setCacheTimesByExpires(long cacheTime, HttpServletResponse response) {
        response.addDateHeader("Expires", cacheTime);
    }

    /**
     * 将毫秒日期精确到秒日期
     * 
     * @param times
     * @return
     */
    public static long changeTimeToSecond(long times) {
        return (times / 1000) * 1000;
    }


}

EtagUtil

/**
 * @author ruby
 * @version 1.0
 * @since
 */
public class EtagUtil {
    public static byte[] serialize(Object obj) throws IOException {
        byte[] byteArray = null;
        ByteArrayOutputStream baos = null;
        ObjectOutputStream out = null;
        try {
            // These objects are closed in the finally.
            baos = new ByteArrayOutputStream();
            out = new ObjectOutputStream(baos);
            out.writeObject(obj);
            byteArray = baos.toByteArray();
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return byteArray;
    }

    public static String getMd5Digest(byte[] bytes) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 cryptographic algorithm is not available.", e);
        }
        byte[] messageDigest = md.digest(bytes);
        BigInteger number = new BigInteger(1, messageDigest);
        // prepend a zero to get a "proper" MD5 hash value
        StringBuffer sb = new StringBuffer('0');
        sb.append(number.toString(16));
        return sb.toString();
    }

    /**
     * 获得etag值
     * 
     * @param obj
     * @return
     */
    public static String getMd5Digest(Object obj) {
        try {
            byte[] bytes = serialize(obj);
            return getMd5Digest(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐