# coding=utf-8
import redis
# 连接池连接(避免每次建立、释放连接的开销)
pool = redis.ConnectionPool(host = 'localhost', port = 6379, db = 0)
red = redis.Redis(connection_pool = pool)
# 在一次请求中指定多个命令
pipe = red.pipeline(transaction = True)
print("设置键和值:", red.set("key", "value")) # 设置键和值
print("获取键对应的值:", red.get("key"))
print("设置键和值,并返回上次操纵的值:", red.getset("key01", "value01"))
print("获取多个键对应的值:", red.mget(["key", "key01"]))
print("如果键不存在,就设置键和值,存在的话就更新:", red.setnx("key02", "value02"))
print("设置键和值,2秒后过期:", red.setex("key03", 2, "value03"))
print("设置键的值,在索引为5的后面补上Hello:", red.setrange("key", 5, "Hello"))
print("修改多个键的名:", red.mset({"key01": "mixintu01", "key02": "mixintu02"}))
print("减均不存在时才批量赋值:", red.msetnx({"sss": "s01", "ddd": "d01"}))
print("键存在值加1,键不存在值设置为-1:", red.incr("key04", 1))
print("键存在值减1,键不存在值设置为-1:", red.decr("key05", 1))
print("向键的值追加OK:", red.append("key06", "OK"))
print("返回键对应值的索引,截取索引为1-4的字符:", red.substr("key07", 1, 4)) # 有默认结束索引,为-1
print("返回键对应值的索引,截取索引为1-4的字符:", red.getrange("key08", 1, 4)) # 无默认结束索引
pipe.execute( ) # 执行管道操作
Redis 字符串操作
最新推荐文章于 2024-03-11 23:42:55 发布
本文详细介绍使用Python的Redis模块进行高效数据操作的方法,包括如何通过连接池避免频繁的连接和断开,利用管道批量执行命令减少网络延迟,以及演示各种数据操作如设置键值、获取键值、设置过期时间等。
921

被折叠的 条评论
为什么被折叠?



