Dhr*_*hak 12 python json redis msgpack
要求:具有2-3级嵌套的Python对象,包含基本数据类型,如整数,字符串,列表和dicts.(没有日期等),需要作为json存储在redis中以对照密钥.什么是可用于将json压缩为低内存占用的字符串的最佳方法.目标对象不是很大,平均有1000个小元素,或者转换为JSON时大约有15000个字符.
例如.
>>> my_dict
{'details': {'1': {'age': 13, 'name': 'dhruv'}, '2': {'age': 15, 'name': 'Matt'}}, 'members': ['1', '2']}
>>> json.dumps(my_dict)
'{"details": {"1": {"age": 13, "name": "dhruv"}, "2": {"age": 15, "name": "Matt"}}, "members": ["1", "2"]}'
### SOME BASIC COMPACTION ###
>>> json.dumps(my_dict, separators=(',',':'))
'{"details":{"1":{"age":13,"name":"dhruv"},"2":{"age":15,"name":"Matt"}},"members":["1","2"]}'
Run Code Online (Sandbox Code Playgroud)
1 /还有其他更好的方法来压缩json以节省redis内存(同时确保轻量级解码).
2/msgpack [http://msgpack.org/]的候选人有多好?
3 /我还要考虑泡菜这样的选择吗?
Alf*_*lfe 14
我们只是gzip用作压缩机.
import gzip
import cStringIO
def decompressStringToFile(value, outputFile):
"""
decompress the given string value (which must be valid compressed gzip
data) and write the result in the given open file.
"""
stream = cStringIO.StringIO(value)
decompressor = gzip.GzipFile(fileobj=stream, mode='r')
while True: # until EOF
chunk = decompressor.read(8192)
if not chunk:
decompressor.close()
outputFile.close()
return
outputFile.write(chunk)
def compressFileToString(inputFile):
"""
read the given open file, compress the data and return it as string.
"""
stream = cStringIO.StringIO()
compressor = gzip.GzipFile(fileobj=stream, mode='w')
while True: # until EOF
chunk = inputFile.read(8192)
if not chunk: # EOF?
compressor.close()
return stream.getvalue()
compressor.write(chunk)
Run Code Online (Sandbox Code Playgroud)
在我们的用例中,我们将结果存储为文件,如您所想.要仅使用内存中的字符串,您还可以使用cStringIO.StringIO()对象作为文件的替代.
我对不同的二进制格式(MessagePack、BSON、Ion、Smile CBOR)和压缩算法(Brotli、Gzip、XZ、Zstandard、bzip2)进行了广泛的比较。
对于我用于测试的 JSON 数据,将数据保留为 JSON 并使用 Brotli 压缩是最佳解决方案。Brotli 具有不同的压缩级别,因此如果您要长时间保留数据,那么使用高级别压缩可能是值得的。如果您坚持的时间不长,那么较低级别的压缩或使用 Zstandard 可能是最有效的。
Gzip 很简单,但几乎肯定会有更快的替代方案,或提供更好的压缩,或两者兼而有之。
您可以在这里阅读我们调查的完整细节:博客文章
根据上面@Alfe的回答,这里是一个将内容保留在内存中的版本(用于网络I / O任务)。我还做了一些更改以支持Python 3。
import gzip
from io import StringIO, BytesIO
def decompressBytesToString(inputBytes):
"""
decompress the given byte array (which must be valid
compressed gzip data) and return the decoded text (utf-8).
"""
bio = BytesIO()
stream = BytesIO(inputBytes)
decompressor = gzip.GzipFile(fileobj=stream, mode='r')
while True: # until EOF
chunk = decompressor.read(8192)
if not chunk:
decompressor.close()
bio.seek(0)
return bio.read().decode("utf-8")
bio.write(chunk)
return None
def compressStringToBytes(inputString):
"""
read the given string, encode it in utf-8,
compress the data and return it as a byte array.
"""
bio = BytesIO()
bio.write(inputString.encode("utf-8"))
bio.seek(0)
stream = BytesIO()
compressor = gzip.GzipFile(fileobj=stream, mode='w')
while True: # until EOF
chunk = bio.read(8192)
if not chunk: # EOF?
compressor.close()
return stream.getvalue()
compressor.write(chunk)
Run Code Online (Sandbox Code Playgroud)
要测试压缩,请尝试:
inputString="asdf" * 1000
len(inputString)
len(compressStringToBytes(inputString))
decompressBytesToString(compressStringToBytes(inputString))
Run Code Online (Sandbox Code Playgroud)