python中调用redis的示例代码
import redis import os import json # Redis服务器的URL,不包含socket_timeout参数 redis_url = "" print(redis_url) # 创建连接池,并显式设置socket_timeout为0.5秒 pool = redis.ConnectionPool.from_url(redis_url, socket_timeout=0.5) # 使用连接池创建Redis连接 r = redis.Redis(connection_pool=pool) # 测试连接,设置一个键值对 r.set('foo', 'bar') # 获取键值对 value = r.get('foo') print(value) print(value.decode('utf-8')) json_object = json.loads(value) print(json.dumps(json_object, ensure_ascii=False)) # 要删除的键的模式 pattern = 'woc:xxx:*' # 使用 SCAN 命令逐步遍历匹配模式的键 cursor = '0' while cursor != 0: cursor, keys = r.scan(cursor=cursor, match=pattern) if keys: r.delete(*keys) print(f"Deleted keys: {keys}") print("Batch deletion completed.")