东方耀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



  1. # -*- coding: utf-8 -*-
  2. __author__ = u'东方耀 微信:dfy_88888'
  3. __date__ = '2020/5/25 下午4:47'
  4. __product__ = 'PyCharm'
  5. __filename__ = 'redis_demo02'


  6. from redis import StrictRedis
  7. import numpy as np
  8. import msgpack_numpy as m

  9. # pip3 install msgpack
  10. # pip3 install msgpack-numpy
  11. # pip3 install redis


  12. # redis-py提供两个类Redis和StrictRedis用于实现Redis的命令,
  13. # StrictRedis用于实现大部分官方的命令,并使用官方的语法和命令
  14. # 简单说,官方推荐使用StrictRedis方法   Strict 严格的
  15. sr = StrictRedis(host="localhost", port=6379, db=2, password=123456)

  16. m.patch()

  17. names = np.array(['dfy', 'dfy02', '430121'])
  18. encodings = np.random.random(size=(3, 128))

  19. print(names.shape, encodings.shape)

  20. lib_type = 'web_user'
  21. # Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.
  22. # 存: True
  23. # 存: True
  24. print("存:", sr.set(name=lib_type+"_names", value=m.packb(names)))
  25. print("存:", sr.set(name=lib_type+"_encodings", value=m.packb(encodings)))

  26. # print(sr.get(name=lib_type+"_names8"))
  27. names2 = m.unpackb(sr.get(name=lib_type+"_names"))
  28. encodings2 = m.unpackb(sr.get(name=lib_type+"_encodings"))
  29. print(names2.shape, encodings2.shape)

  30. np.testing.assert_equal(names, names2)
  31. np.testing.assert_equal(encodings, encodings2)
  32. assert encodings.dtype == encodings2.dtype

  33. print((names == names2).all())
  34. print((encodings == encodings2).all())


  35. # 判断键是否存在,如果存在返回1,不存在返回0
  36. # print(sr.exists(lib_type))
  37. #
  38. # print(sr.delete(lib_type))
  39. # 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