东方耀AI技术分享
标题:
利用redis和msgpack对ndarray数据序列化(高效读写)
[打印本页]
作者:
东方耀
时间:
2020-5-26 20:06
标题:
利用redis和msgpack对ndarray数据序列化(高效读写)
利用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
复制代码
作者:
东方耀
时间:
2020-5-26 20:08
# Redis 存储数组
# Redis 是不可以直接存储数组的,如果直接存储数组类型的数值,则报错
# 如下,存入 numpy 数组类型,会报错:
# redis.exceptions.DataError: Invalid input of type: 'ndarray'. Convert to a bytes, string, int or float first
# 在存储数组之前将其序列化,获取数组的时候将其反序列化即可。
# 借助于 python 的pickle模块进行序列化操作
欢迎光临 东方耀AI技术分享 (http://www.ai111.vip/)
Powered by Discuz! X3.4