日志服务将日志投递到 TOS 时,将自动运用 Snappy 压缩 TOS 文件。日志投递成功后,您可以通过 C++、Java、Python、Go 等语言相关的工具解压 TOS 文件。
Debian/Ubuntu 方式
sudo apt update sudo apt install libsnappy1v5 libsnappy-dev
CentOS 方式
sudo yum update sudo yum install snappy snappy-devel
Mac 方式
brew install snappy
手动安装方式
下载 Snappy Lib。
安装 Snappy Lib。
git clone https://github.com/google/snappy make && make install
说明
手动安装的库可能不会被系统自动识别,需要手动添加库路径。
int main() { std::string decompressed; // 读取压缩数据并解压 std::ifstream inFile("compressed.snappy", std::ios::binary); std::string readCompressed((std::istreambuf_iterator<char>(inFile)), std::istreambuf_iterator<char>()); inFile.close(); // 解压 snappy::Uncompress(readCompressed.data(), readCompressed.size(), &decompressed); std::cout << "Decompressed text: " << decompressed << "\n"; return 0; }
下载依赖包。
说明
推荐使用 1.1.2.6 及以上版本的 Java Lib。因为 1.1.2.1 版本存在 Bug ,可能无法解压部分压缩文件,1.1.2.6 及以上版本已修复该问题。关于该 Bug 的更多信息,请参见bad handling of the MAGIC HEADER。
<dependency> <groupId>org.xerial.snappy</groupId> <artifactId>snappy-java</artifactId> <version>1.1.10.4</version> <type>jar</type> <scope>compile</scope> </dependency>
解压文件。
代码示例如下:
package main; import org.xerial.snappy.Snappy; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; public class SnappyCompressionDemo { public static void main(String[] args) throws Exception { String compressedFilePath = "compressed.snappy"; // 从文件读取压缩数据 byte[] readCompressedData = Files.readAllBytes(Paths.get(compressedFilePath)); // 解压缩数据 byte[] decompressedData = Snappy.uncompress(readCompressedData); // 输出解压缩的数据 String decompressedString = new String(decompressedData); System.out.println("Decompressed data: " + decompressedString); } }
下载依赖包 python-lib。
安装 pip。
pip install python-snappy
解压文件。
python3 代码示例如下:
import snappy def demo(): # 读取压缩数据 with open("compressed.snappy", "rb") as in_file: read_compressed = in_file.read() # 解压缩数据 decompressed = snappy.uncompress(read_compressed) print(f"Decompressed data: {decompressed.decode('utf-8')}") if __name__ == "__main__": demo()
说明
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence
错误,可能是因为 Windows 文件系统以 BOM 开头。建议您使用类 Unix 系统或者在 open 函数的 encoding 中设置正确的文件编码。python -m snappy -d compressed_file.snappy uncompressed_file
下载依赖包 go-snappy。
安装依赖包。
go get github.com/golang/snappy go mod tidy
解压文件。
代码示例如下:
package main import ( "fmt" "log" "os" "github.com/golang/snappy" ) func main() { // 从文件读取压缩数据 readCompressed, err := os.ReadFile("compressed.snappy") if err != nil { log.Fatalf("Failed to read compressed file: %v", err) } // 解压数据 decompressed, err := snappy.Decode(nil, readCompressed) if err != nil { log.Fatalf("Failed to decompress data: %v", err) } fmt.Printf("Decompressed data: %s\n", string(decompressed)) }