Python自动化操作Redis的15个实用脚本
Python自动化操作Redis的15个实用脚本Redis作为高性能的键值数据库在现代应用开发中扮演着重要角色。Python通过redis-py库提供了丰富的Redis操作接口能够帮助开发者高效地实现数据缓存、会话管理、消息队列等多种功能。本文将介绍15个实用的自动化脚本涵盖数据操作、性能优化和高级功能等多个典型场景。环境准备首先确保已安装redis-py库pip install redis所有示例默认连接本地Redis服务器localhost:6379数据库0实际使用时请根据生产环境调整连接参数。1. 基础键值操作场景简单的数据存储与检索import redis def basic_key_operations(): r redis.Redis(hostlocalhost, port6379, db0) # 设置带过期时间的键值 r.setex(session:user123, 3600, active) # 获取值 status r.get(session:user123) print(fSession status: {status.decode() if status else Not found}) # 检查键是否存在 exists r.exists(session:user123) print(fKey exists: {exists}) if __name__ __main__: basic_key_operations()2. 批量操作键值场景高效处理大量数据def batch_operations(): r redis.Redis(hostlocalhost, port6379, db0) # 批量设置多个键值 data { user:1:name: Alice, user:1:email: aliceexample.com, user:1:age: 25 } r.mset(data) # 批量获取多个键值 keys [user:1:name, user:1:email, user:1:age] values r.mget(keys) for key, value in zip(keys, values): print(f{key}: {value.decode() if value else None})3. 哈希表高级操作场景存储结构化对象def advanced_hash_operations(): r redis.Redis(hostlocalhost, port6379, db0) user_id user:1001 # 设置多个字段 user_data { name: Bob Smith, email: bobexample.com, score: 95, last_login: 2025-12-25 } r.hset(user_id, mappinguser_data) # 获取所有字段 all_fields r.hgetall(user_id) print(User data:) for field, value in all_fields.items(): print(f {field.decode()}: {value.decode()}) # 增加数值字段 r.hincrby(user_id, score, 5) new_score r.hget(user_id, score) print(fUpdated score: {new_score.decode()})4. 列表队列操作场景实现任务队列def queue_operations(): r redis.Redis(hostlocalhost, port6379, db0) queue_key task_queue # 生产者添加任务到队列 tasks [process_data, send_email, generate_report, cleanup] for task in tasks: r.lpush(queue_key, task) print(fAdded task: {task}) # 消费者处理任务 while True: task r.brpop(queue_key, timeout1) if task: task_name task[1].decode() print(fProcessing task: {task_name}) # 模拟任务处理 import time time.sleep(0.5) print(fCompleted: {task_name}) else: print(No more tasks in queue) break5. 集合运算场景用户标签系统def set_operations(): r redis.Redis(hostlocalhost, port6379, db0) # 用户标签集合 r.sadd(user:101:tags, python, redis, backend) r.sadd(user:102:tags, python, frontend, javascript) r.sadd(user:103:tags, redis, database, backend) # 查找共同标签 common_tags r.sinter(user:101:tags, user:103:tags) print(Common tags between user 101 and 103:) for tag in common_tags: print(f - {tag.decode()}) # 合并所有标签 all_tags r.sunion(user:101:tags, user:102:tags, user:103:tags) print(\nAll unique tags:) for tag in sorted(all_tags): print(f - {tag.decode()})6. 有序集合排行榜场景游戏得分排行榜def leaderboard_system(): r redis.Redis(hostlocalhost, port6379, db0) leaderboard_key game:leaderboard # 添加玩家得分 players { player1: 1500, player2: 2200, player3: 1800, player4: 2500, player5: 1900 } r.zadd(leaderboard_key, players) # 获取前3名 top_players r.zrevrange(leaderboard_key, 0, 2, withscoresTrue) print(Top 3 Players:) for rank, (player, score) in enumerate(top_players, 1): print(f{rank}. {player.decode()}: {int(score)} points) # 获取玩家排名 player_rank r.zrevrank(leaderboard_key, player3) player_score r.zscore(leaderboard_key, player3) print(f\nPlayer3 rank: {player_rank 1 if player_rank is not None else N/A}) print(fPlayer3 score: {player_score})7. 发布订阅模式场景实时通知系统import threading import time def pubsub_system(): r redis.Redis(hostlocalhost, port6379, db0) def subscriber(channel_name): pubsub r.pubsub() pubsub.subscribe(channel_name) print(fSubscriber started on channel: {channel_name}) for message in pubsub.listen(): if message[type] message: data message[data].decode() print(fReceived: {data}) if data exit: break # 启动订阅者线程 channel notifications sub_thread threading.Thread(targetsubscriber, args(channel,)) sub_thread.daemon True sub_thread.start() time.sleep(1) # 等待订阅者准备 # 发布消息 messages [ System started, User logged in, Data updated, exit ] for msg in messages: r.publish(channel, msg) time.sleep(0.5) sub_thread.join(timeout2)8. 管道批量操作场景减少网络延迟def pipeline_performance(): r redis.Redis(hostlocalhost, port6379, db0) # 不使用管道 start time.time() for i in range(100): r.set(ftemp:{i}, fvalue:{i}) without_pipeline time.time() - start # 清理数据 for i in range(100): r.delete(ftemp:{i}) # 使用管道 start time.time() pipe r.pipeline() for i in range(100): pipe.set(ftemp:{i}, fvalue:{i}) pipe.execute() with_pipeline time.time() - start print(fWithout pipeline: {without_pipeline:.3f} seconds) print(fWith pipeline: {with_pipeline:.3f} seconds) print(fPerformance improvement: {without_pipeline/with_pipeline:.1f}x)9. 事务保证原子性场景账户余额转账def transaction_example(): r redis.Redis(hostlocalhost, port6379, db0) # 初始化账户余额 r.set(account:A, 1000) r.set(account:B, 500) def transfer_funds(from_account, to_account, amount): pipe r.pipeline(transactionTrue) try: # 监视账户变化 pipe.watch(from_account, to_account) # 检查余额 from_balance int(pipe.get(from_account) or 0) if from_balance amount: print(Insufficient funds) return False # 开始事务 pipe.multi() pipe.decrby(from_account, amount) pipe.incrby(to_account, amount) pipe.execute() print(fTransferred {amount} from {from_account} to {to_account}) return True except redis.WatchError: print(Transaction failed due to concurrent modification) return False finally: pipe.reset() # 执行转账 transfer_funds(account:A, account:B, 200) # 验证结果 print(fAccount A: {r.get(account:A).decode()}) print(fAccount B: {r.get(account:B).decode()})10. Lua脚本执行场景复杂原子操作def lua_scripting(): r redis.Redis(hostlocalhost, port6379, db0) # Lua脚本原子性地检查并设置值 lua_script local key KEYS local value ARGV local ttl ARGV local current redis.call(GET, key) if current then return {false, current} else redis.call(SET, key, value) redis.call(EXPIRE, key, ttl) return {true, value} end # 注册脚本 script r.register_script(lua_script) # 执行脚本 key cache:item result script(keys[key], args[cached_data, 60]) if result[0]: print(fCache set successfully: {result[1]}) else: print(fCache already exists: {result[1]})11. 键过期与TTL管理场景缓存失效管理def expiration_management(): r redis.Redis(hostlocalhost, port6379, db0) # 设置带过期时间的键 cache_key api:response:user:123 r.setex(cache_key, 300, {name: John, status: active}) # 5分钟过期 # 检查剩余时间 ttl r.ttl(cache_key) print(fCache will expire in {ttl} seconds) # 更新过期时间 if ttl 60: # 如果剩余时间小于1分钟 r.expire(cache_key, 600) # 延长到10分钟 print(Cache expiration extended to 10 minutes) # 设置永久键 r.set(config:site_name, MyApp) r.persist(config:site_name) # 移除过期时间12. 扫描大键集合场景安全遍历大量键def scan_keys(): r redis.Redis(hostlocalhost, port6379, db0) # 使用SCAN代替KEYS避免阻塞 pattern user:* cursor 0 user_keys [] while cursor ! 0: cursor, keys r.scan(cursorcursor, matchpattern, count100) user_keys.extend(keys) print(fFound {len(user_keys)} user keys) # 批量获取用户信息 for i in range(0, len(user_keys), 10): batch user_keys[i:i10] values r.mget(batch) for key, value in zip(batch, values): if value: print(f{key.decode()}: {value.decode()[:50]}...)13. 位图操作场景用户在线状态追踪def bitmap_operations(): r redis.Redis(hostlocalhost, port6379, db0) # 记录用户每日登录状态 bitmap_key online:2025-12-25 # 用户ID 1001-1010在25日登录 for user_id in range(1001, 1011): r.setbit(bitmap_key, user_id, 1) # 检查特定用户是否登录 user_1005_status r.getbit(bitmap_key, 1005) print(fUser 1005 online: {Yes if user_1005_status else No}) # 统计在线用户数 online_count r.bitcount(bitmap_key) print(fTotal online users: {online_count}) # 查找第一个在线的用户 first_online r.bitpos(bitmap_key, 1) print(fFirst online user ID: {first_online})14. 地理空间索引场景附近位置搜索def geospatial_operations(): r redis.Redis(hostlocalhost, port6379, db0) # 添加地理位置 locations_key cities:locations cities { Beijing: (116.4074, 39.9042), Shanghai: (121.4737, 31.2304), Guangzhou: (113.2644, 23.1291), Shenzhen: (114.0579, 22.5431) } r.geoadd(locations_key, cities) # 查找附近的城市 center (116.4074, 39.9042) # 北京坐标 nearby r.georadius( locations_key, center[0], center[1], 500, # 500公里半径 unitkm, withdistTrue, sortASC ) print(Cities within 500km of Beijing:) for city, distance in nearby: print(f {city.decode()}: {distance:.1f} km) # 计算两个城市距离 distance r.geodist(locations_key, Beijing, Shanghai, unitkm) print(f\nDistance Beijing-Shanghai: {distance} km)15. 连接池与连接管理场景生产环境连接优化import redis from redis.connection import ConnectionPool def connection_pool_management(): # 创建连接池 pool ConnectionPool( hostlocalhost, port6379, db0, max_connections10, socket_timeout5, retry_on_timeoutTrue ) # 使用连接池 r redis.Redis(connection_poolpool) try: # 测试连接 r.ping() print(Redis connection successful) # 性能测试 import time start time.time() for i in range(1000): r.set(ftest:{i}, fdata:{i}) elapsed time.time() - start print(f1000 operations completed in {elapsed:.2f} seconds) print(fOperations per second: {1000/elapsed:.0f}) except redis.ConnectionError as e: print(fConnection failed: {e}) finally: # 清理连接池 pool.disconnect() print(Connection pool cleaned up)这些脚本覆盖了Redis主要应用场景从基础操作到高级功能可以帮助开发者高效地实现各种数据存储和处理需求。在实际应用中建议根据具体业务场景选择合适的操作方式并结合性能监控和优化策略可以显著提升应用性能和开发效率。“无他惟手熟尔”有需要的用起来关注「Nicholas与Pypi」获取更多Python实战

相关新闻

对话文本理解技术:从命名实体识别到情感分析完整指南

对话文本理解技术:从命名实体识别到情感分析完整指南

最近在开发一个智能对话系统时,我遇到了一个很有意思的问题:当用户输入"孙悟空说:你这老头真是有眼无珠,认不得真神!"这样的对话文本时,系统应该如何准确理解其中的语义层次和情感色彩&#xff1…

2026/10/6 19:21:43 阅读更多 →
桥式铆接电池弹片哪个厂家靠谱

桥式铆接电池弹片哪个厂家靠谱

桥式铆接电池弹片,到底选哪家?我做这行10年的真心话“老张,你之前那批桥式铆接电池弹片,用了一个月就出问题了吧?”上周在行业展会上,同行一句话让我想起三年前的教训。那时候,我贪便宜&#xf…

2026/10/6 21:33:40 阅读更多 →
电源PCB设计实战:开关电源与LDO布局布线全解析

电源PCB设计实战:开关电源与LDO布局布线全解析

1. 电源PCB设计的核心挑战与解决思路 电源电路作为电子系统的"心脏",其PCB设计质量直接影响整个产品的稳定性和可靠性。从业十余年,我见过太多因为电源设计不当导致的系统崩溃案例——从简单的LDO发热异常,到复杂的开关电源EMI超标…

2026/10/7 1:07:17 阅读更多 →

最新新闻

Diagram-as-Code:用代码写图实现设计即代码

Diagram-as-Code:用代码写图实现设计即代码

1. 项目概述:这不是画图,是构建可演进的系统表达语言“diagram-design”这四个字乍看像一个工具栏里的功能按钮,但在我过去十年带团队做技术方案设计、系统架构评审和跨职能协作的过程中,它早已不是“用Visio拖几个方块”的代名词…

2026/10/15 9:06:37 阅读更多 →
GL3224读卡器主控实战:USB 3.1 UHS-I设计调试全攻略

GL3224读卡器主控实战:USB 3.1 UHS-I设计调试全攻略

简介:GL3224 USB3.1 Gen1 CardReader Controller 数据手册,面向硬件工程师、嵌入式开发者和读卡器方案设计人员,解决高速读卡器控制器的选型、电路连接与调试问题,是SD4.0读卡器方案开发中不可绕过的主控参考文档。手册基于Genesy…

2026/10/15 9:06:37 阅读更多 →
SpringBoot+Vue构建高并发数码商城的实战指南

SpringBoot+Vue构建高并发数码商城的实战指南

1. 项目概述数码产品购物商城是一个典型的B2C电商平台,专注于3C数码产品在线销售。这个基于SpringBootVue的前后端分离项目,是我在开发实践中总结出的一套高可用电商解决方案。相比传统单体架构,这种分离设计让前端展示更灵活,后端…

2026/10/15 9:06:37 阅读更多 →
电影级AI影像生产闭环:GPT-6+Runway+Seedance+DaVinci工作流

电影级AI影像生产闭环:GPT-6+Runway+Seedance+DaVinci工作流

1. 这不是“AI剪辑”,而是一套可落地的电影级影像生产闭环最近在几个影视制作群和AIGC创作者圈子里,总有人甩出一句话:“现在做短片,真不用养剪辑师了。”起初我以为是夸张,直到亲眼看到一位独立导演用不到72小时&…

2026/10/15 9:06:37 阅读更多 →
神经操作系统:Runway如何用隐空间重构工业智能体

神经操作系统:Runway如何用隐空间重构工业智能体

1. 这不是又一个“AI视频工具”的故事,而是Runway在重构智能体底层逻辑你点开Runway官网,第一眼看到的还是Gen-3那几段丝滑到令人屏息的视频生成demo——镜头推拉自然、光影过渡真实、角色动作连贯。但如果你真以为Runway只是个“做视频的AI公司”&#…

2026/10/15 9:06:37 阅读更多 →
基因组测序技术在多倍体与杂合基因组组装中的突破与应用

基因组测序技术在多倍体与杂合基因组组装中的突破与应用

1. 项目背景与行业痛点基因组测序技术在过去二十年里经历了从"奢侈品"到"常规工具"的转变。2010年完成一个人类基因组测序还需要数万美元,而如今同样的工作仅需几百美元就能完成。这种成本下降使得基因组测序从人类医学领域迅速扩展到动植物研究…

2026/10/15 9:05:35 阅读更多 →

日新闻

Docker Compose 容器化部署 ChirpStack LoRaWAN 网络服务器实战

Docker Compose 容器化部署 ChirpStack LoRaWAN 网络服务器实战

1. 为什么选择容器化方式部署 LoRa 网络服务LoRa 物联网项目落地时,网络服务器是整个链路的核心枢纽。它负责接收网关上报的数据包、完成去重与解密、再把有效载荷分发给上层应用。早期大家习惯把网络服务器直接装在物理机上,依赖一堆系统库和特定版本的…

2026/10/15 0:00:46 阅读更多 →
共享LLM服务下的跨模型自动扩缩容:Kubernetes实战与避坑指南

共享LLM服务下的跨模型自动扩缩容:Kubernetes实战与避坑指南

1. 共享推理服务里,扩缩容到底难在哪做过大模型推理服务部署的人,大概都经历过这样的场景:一个团队共用一套推理集群,A 业务跑的是 7B 的小模型,B 业务跑的是 72B 的大模型,C 业务白天流量高、晚上几乎归零…

2026/10/15 0:00:46 阅读更多 →
Systemd 启动阶段根文件系统只读之谜:fstab 与 remount-fs 服务深度解析

Systemd 启动阶段根文件系统只读之谜:fstab 与 remount-fs 服务深度解析

1. 引子:一次内核恐慌引发的追查先从一个真实场景说起。某次我给一台老旧的嵌入式设备折腾系统裁减,为了把启动时间压进两秒以内,我手贱地把一串自认为“没用”的 systemd 服务给 disable 了,其中就包括systemd-remount-fs.servic…

2026/10/15 0:00:46 阅读更多 →

周新闻

流感时间序列预测实战:ARIMA/LSTM全流程拆解与避坑指南

流感时间序列预测实战:ARIMA/LSTM全流程拆解与避坑指南

简介:基于 ARIMA、LSTM、Transformer 等模型的流感时间序列预测 Python 源码,面向计算机相关专业课程设计与期末大作业学生,以及项目实战学习者。内容覆盖预处理、平稳性检验、定阶、残差分析、多模型对比预测的完整时序建模流程,…

2026/10/14 3:30:28 阅读更多 →
影刀RPA新手教程:键盘模拟输入实战——输入文本与模拟按键的区别

影刀RPA新手教程:键盘模拟输入实战——输入文本与模拟按键的区别

影刀RPA新手教程:键盘模拟输入实战——输入文本与模拟按键的区别 做影刀RPA自动化,十个新手有八个栽在"往输入框里填东西"这件事上:要么填不进去,要么填了一半,要么直接把原来内容追加在后面。这背后的根因&…

2026/10/14 16:30:29 阅读更多 →
影刀RPA新手教程:阅文起点小说数据采集实战——书籍信息与章节内容

影刀RPA新手教程:阅文起点小说数据采集实战——书籍信息与章节内容

影刀RPA新手教程:阅文起点小说数据采集实战——书籍信息与章节内容 1. 认识影刀:什么场景该用RPA采小说数据 起点中文网的页面结构相对稳定——分类榜单、书籍详情、章节内容三块独立页面,跳转链路清晰。这种场景非常适合影刀自动化&#x…

2026/10/14 3:29:58 阅读更多 →

月新闻

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

我发现了一个新思路:用 Remotion + Claude Code 像写代码一样自动化生成短视频

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/15 0:14:36 阅读更多 →
Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

Windows下 Codex 中 Chrome 和 Computer Use 插件不可用问题排查及解决参考方式:TaoToken 统一 Key 配置与验证

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/14 22:45:47 阅读更多 →
黑夜航拍船只数据集训练YOLOV5模型全流程解析

黑夜航拍船只数据集训练YOLOV5模型全流程解析

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/10/14 7:53:34 阅读更多 →