文件压缩有两个好处
1.减少存储文件的所需的磁盘空间
2.加少数据在网络和磁盘上的传输
在hadoop中文件压缩方式有很多种,各有千秋
压缩要权衡空间和时间两个维度,虽然减少了空间,但增加了cpu的使用率
gzip是个通用的压缩工具,在空间和时间性能上居中,后面有案例测试。
Codec是压缩-解压缩算法的一种实现
举例测试
将指定文件调用hadoop压缩方法进行压缩
导包:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.compress.*;
import org.apache.hadoop.util.ReflectionUtils;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
实现:
@Test
public void testCompress() throws Exception {
Configuration conf = new Configuration();
Class[] codecClass = new Class[4];
codecClass[0] = DeflateCodec.class;
codecClass[1] = GzipCodec.class;
codecClass[2] = BZip2Codec.class;//可拆分
codecClass[3] = Lz4Codec.class;
for (Class c1 : codecClass) {
Long start=System.currentTimeMillis();
FileInputStream in = new FileInputStream("d:/data-200W.csv");
CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(c1, conf);
FileOutputStream dest = new FileOutputStream("d:/hadoop_test/wcout/test" + codec.getDefaultExtension());
CompressionOutputStream zipOut = codec.createOutputStream(dest);
IOUtils.copyBytes(in,zipOut,1024);
zipOut.close();
System.out.println("=============================================");
System.out.println("压缩方式:"+c1.getSimpleName()+",耗时:"+(System.currentTimeMillis()-start));
}
}
本次测试结果:
原始文件data-200W.csv 的大小是332M
压缩方式 | 压缩时间(毫秒) | 压缩后大小 |
Deflate | 25176 | 122M |
Gzip | 25143 | 122M |
BZip2 | 304460 | 82.4M |
Lz4 | 3295 | 188M |
网上找的图片
综合来说,gzip居优