python操作redis的方法有哪些
作者:OpenWorld
时间:2023-04-28
来源:互联网
浏览:0
python操作redis,使用连接池:redis-py使用connectionpool来管理对一个redisserver的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池。defgetcoon():pool=redis.ConnectionPool(host='192.168.25.126',port=6379,password='123456&
python 操作redis,使用连接池:
redis-py使用connection pool来管理对一个redis server的所有连接,避免每次建立、释放连接的开销。默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池。
def getcoon():
pool = redis.ConnectionPool(host='192.168.25.126', port=6379, password='123456', db=0)
coon = redis.Redis(connection_pool=pool)
coon.set('key', 'value')
res = coon.get('key')
return rescoon.set('sea', 'hahhahaha', ex=30) # 过期时间单位sset(name, value, ex=None, px=None, nx=False, xx=False) 在 Redis 中设置值,默认,不存在则创建,存在则修改。 参数: ex - 过期时间(秒) px - 过期时间(毫秒) nx - 如果设置为True,则只有name不存在时,当前set操作才执行 xx - 如果设置为True,则只有name存在时,当前set操作才执行
redis 使用连接池操作
class OPRedis(object):
def __init__(self):
if not hasattr(OPRedis, 'pool'):
OPRedis.getRedisCoon() #创建redis连接
self.coon = redis.Redis(connection_pool=OPRedis.pool)
@staticmethod
def getRedisCoon():
OPRedis.pool = redis.ConnectionPool(host=redisInfo['host'], password=redisInfo['password'], port=redisInfo['port'], db=redisInfo['db'])
"""
string类型 {'key':'value'} redis操作
"""
def setredis(self, key, value, time=None):
#非空即真非0即真
if time:
res = self.coon.setex(key, value, time)
else:
res = self.coon.set(key, value)
return res
def getRedis(self, key):
res = self.coon.get(key).decode()
return res
def delRedis(self, key):
res = self.coon.delete(key)
return res
"""
hash类型,{'name':{'key':'value'}} redis操作
"""
def setHashRedis(self, name, key, value):
res = self.coon.hset(name, key, value)
return res
def getHashRedis(self, name, key=None):
# 判断key是否我为空,不为空,获取指定name内的某个key的value; 为空则获取name对应的所有value
if key:
res = self.coon.hget(name, key)
else:
res = self.coon.hgetall(name)
return res
def delHashRedis(self, name, key=None):
if key:
res = self.coon.hdel(name, key)
else:
res = self.coon.delete(name)
return resredisInfo配置
redisInfo = {
"host": '192.168.1.112',
"password": '123456',
"port": 6379,
"db": 0
}
作者最新文章
三星 Galaxy A08 渲染图曝光:Helio G99 芯片与 6000mAh 电池配置解析
2026-09-08 17:14
OPPO Find X10 Pro Max 影像规格详解:三颗2亿像素镜头与全焦段8K视频能力
2026-09-08 16:41
PDF转HTML在线转换器怎么选?转换后网页排版怎么查?
2026-09-04 11:02
AE教程书籍挑选指南:零基础、动效与合成方向实战标准
2026-09-02 13:31
教程书籍使用SAI软件Logo要单独授权吗:商标引用与出版合规要点
2026-09-02 11:50
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















