|
利用redis和msgpack对ndarray数据序列化(高效读写)
# pip3 install msgpack
# pip3 install msgpack-numpy
# pip3 install redis
- # -*- coding: utf-8 -*-
- __author__ = u'东方耀 微信:dfy_88888'
- __date__ = '2020/5/25 下午4:47'
- __product__ = 'PyCharm'
- __filename__ = 'redis_demo02'
- from redis import StrictRedis
- import numpy as np
- import msgpack_numpy as m
- # pip3 install msgpack
- # pip3 install msgpack-numpy
- # pip3 install redis
- # redis-py提供两个类Redis和StrictRedis用于实现Redis的命令,
- # StrictRedis用于实现大部分官方的命令,并使用官方的语法和命令
- # 简单说,官方推荐使用StrictRedis方法 Strict 严格的
- sr = StrictRedis(host="localhost", port=6379, db=2, password=123456)
- m.patch()
- names = np.array(['dfy', 'dfy02', '430121'])
- encodings = np.random.random(size=(3, 128))
- print(names.shape, encodings.shape)
- lib_type = 'web_user'
- # Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.
- # 存: True
- # 存: True
- print("存:", sr.set(name=lib_type+"_names", value=m.packb(names)))
- print("存:", sr.set(name=lib_type+"_encodings", value=m.packb(encodings)))
- # print(sr.get(name=lib_type+"_names8"))
- names2 = m.unpackb(sr.get(name=lib_type+"_names"))
- encodings2 = m.unpackb(sr.get(name=lib_type+"_encodings"))
- print(names2.shape, encodings2.shape)
- np.testing.assert_equal(names, names2)
- np.testing.assert_equal(encodings, encodings2)
- assert encodings.dtype == encodings2.dtype
- print((names == names2).all())
- print((encodings == encodings2).all())
- # 判断键是否存在,如果存在返回1,不存在返回0
- # print(sr.exists(lib_type))
- #
- # print(sr.delete(lib_type))
- # set成功 返回True
复制代码
|
|