Cookie压缩。

Cookie在HTTP的头部,所以通常的gzip和deflate针对HTTP Body的压缩不能压缩Cookie,如果Cookie的量非常大,则可以考虑将Cookie也做压缩,压缩方式是将Cookie的多个k/v对看成普通的文本,做文本压缩。压缩算法同样可以使用gzip和deflate算法,但是需要注意的一点是,根据Cookie的规范,在Cookie中不能包含控制字符,仅能包含ASCII码为34~126的可见字符。所以要将压缩后的结果再进行转码,可以进行Base32或者Base64编码。

可以配置一个Filter在页面输出时对Cookie进行全部或者部分压缩,如下所示:

private void compressCookie(Cookie c, HttpServletResponse res) {
    try {
        ByteArrayOutputStream bos = null;
        bos = new ByteArrayOutputStream();
        DeflaterOutputStream dos = new DeflaterOutputStream();
        dos.write(c.getValue().getBytes());
        dos.close();
        System.out.println("before compress length:" + c.getValue().getBytes().length);
        String compress = new sun.misc.BASE64Encoder().encode(bos.toByteArray());
        res.addCookie(new Cookie("compress",compress));
        System.out.println("after compress length:" + compress.getBytes().length);
    } catch(IOException e) {
        e.printStackTrace();
    }
}

上面的代码是用DeflaterOutputStream对Cookie进行压缩的,Deflater压缩后再进行BASE64编码,相应的用InflaterInputStream进行解压。

private void unCompressCookie(Cookie c) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] compress = new sun.misc.BASE64Decoder().decodeBuffer(new String(c.getValue().getBytes()));
        ByteArrayInputStream bis = new ByteArrayInputStream(compress);
        InflaterInputStream inflater = new InflaterInputStream(bis);
        byte[] b = new byte[1024];
        int count;
        while((count = inflater.read(b)) >= 0) {
            out.write(b, 0, count);
        }
        inflater.close();
        System.out.println(out.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2KB大小的Cookie在压缩前与压缩后的字节数相差20%左右,如果你的网站的Cookie在2~3KB左右,一天有1亿的PV,那么一天就能够产生4TB的带宽流量了,从节省带宽成本来说压缩还是很有必要的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值