Redis——使用 python 操作 redis 之从 hmse 迁移到 hset

环境

问题描述

我想向一个 hash 类型的 key 中插入多个 键值对 value。

在 redis-cli 中我可以使用 HMSET 命令实现这种批量插入,但是当我使用 redis library 4.1.4 中的 hmset 方法时报错:DeprecationWarning: Redis.hmset() is deprecated. Use Redis.hset() instead. conn.hmset(article, content)

代码如下:

复制代码
import time
import redis3

conn = redis3.Redis(host='localhost', port=6379, db=0, decode_responses=True)
conn.flushdb()

now = time.time()
article = 'article:' + str(1)

content = {
    'title': 'A title',
    'link': 'http://www.google.com',
    'poster': 'username',
    'time': now,
    'votes': 1,
}

conn.hmset(article, content)
print(conn.hgetall(article))

查了一下,根据hmset() uses deprecated command HMSET #1269的说法, hmset 方法从 4.0.0 版本开始就被弃用了。

尽管这里报错,但实际上它还是起作用了,因为它并没有被从 redis library 4.1.4 的 API 源码中移出。

因为它早晚会被移除,我就想从 hmse 迁移到 hset,于是这就产生了一些问题:

  • 怎样使用 hset API。
  • 在使用 hset API时遇到了一些问题。

解决过程

过程及方法一:

使用循环,但这样在处理大数据时会比较慢:

复制代码
from pyinstrument import Profiler
profiler=Profiler()
profiler.start()
for i in range(100000):
    for item in content:
        conn.hset(article, item, content[item])
profiler.stop()
profiler.print()

执行性能如下:

复制代码
  _     ._   __/__   _ _  _  _ _/_   Recorded: 18:10:52  Samples:  41159
 /_//_/// /_ / //_// / //_'/ //     Duration: 41.370    CPU time: 38.547
/   _/                      v4.1.1

Program: F:/python基础/操作数据库/redis/test.py

41.366 <module>  test.py:8
└─ 40.991 hset  redis3client.py:3034
      [130 frames hidden]  redis3, <built-in>
         8.293 socket.sendall  <built-in>:0

过程及方法二:

根据源码以及hset mapping not working #1396的说法,我使用mapping参数映射一下:

复制代码
conn.hset(article, mapping=content)

但报错:redis3.exceptions.ResponseError: wrong number of arguments for 'hset' command

按照 redis doc:hset 的说法,mapping 参数应该是支持以 python 字典形式插入 hash 类型的数据的,就在想是不是本地 windows redis 版本的问题,根据[BUG] hset does not support multiple dict mapping #8622中的讨论,去查了一下本地 windows redis 版本:

好家伙,版本太低了,要么直接卸载,然后手动编译重装 6.X 版本,要么还是在 linux 环境操作:

复制代码
# 查看redis版本
dfl@WEB:/opt/redis-6.0.9$ redis-cli
127.0.0.1:6379> info server
# Server
redis_version:6.0.9

执行官结果如下:

复制代码
{'title': 'A title', 'link': 'http://www.google.com', 'poster': 'username', 'time': '1648130581.633493', 'votes': '1'}

过程及方法三:

Redis 大量数据插入

相关推荐
landyjzlai9 小时前
蓝迪哥玩转Ai(8)---端侧AI:RK3588 端侧大语言模型(LLM)开发实战指南
人工智能·python
S1998_1997111609•X11 小时前
论当今社会主义与人文关怀人格思想下的恶意仿生注入污染蜜罐描述进行函数值非法侵入爬虫的咼忄乂癿〇仺⺋.
数据库·网络协议·百度·ssh·开闭原则
我叫黑大帅11 小时前
如何通过 Python 实现招聘平台自动投递
后端·python·面试
其实防守也摸鱼11 小时前
CTF密码学综合教学指南--第九章
开发语言·网络·python·安全·网络安全·密码学·ctf
砚底藏山河12 小时前
Python量化开发:2026最佳实时股票数据API接口推荐与对比
开发语言·windows·python
倔强的石头_12 小时前
kingbase备份与恢复实战(六)—— 备份自动化与保留策略:Windows任务计划+日志追溯
数据库
研究点啥好呢12 小时前
专为求职者开发的“面馆”!!!摆脱面试焦虑!!!
python·面试·开源·reactjs·求职招聘·fastapi
轻刀快马13 小时前
别被 ORM 框架宠坏了:从一场“订单消失”悬案,看懂 MySQL 为什么要强推 InnoDB
数据库·mysql
DFT计算杂谈13 小时前
自动化脚本一键绘制三元化合物相图
java·运维·服务器·开发语言·前端·python·自动化
EW Frontier14 小时前
6G ISAC新范式:基于智能漏波天线的Wi‑Fi通感一体化系统设计与实测【附MATLAB+python代码】
开发语言·python·matlab·music·isac·doa·wi‑fi