当前位置: 移动技术网 > IT编程>脚本编程>Python > python连接redis的两种方式

python连接redis的两种方式

2020年07月03日  | 移动技术网IT编程  | 我要评论

前言

------先安装redis库
------pip install redis

  • 直接连接,用redis库中的Redis或者StrictRedis
  • 连接池连接,跟直接连接操作步骤相似,只是要传入pool参数

代码


第一种
from redis import Redis

'''
    一般连接,使用Redis连接
'''

# 这里使用Redis
db = Redis(host="localhost", port=6379, db=0, decode_responses=True)
# 操作结果的数据类型默认为二进制,除非decode_responses=True
resu = db.smembers('set1')
print(resu)

from redis import StrictRedis

'''
    一般连接,使用StrictRedis连接
'''

# 这里使用StrictRedis
db = StrictRedis(host="localhost", port=6379, db=0, decode_responses=True)


第二种
from redis import ConnectionPool
from redis import Redis

'''
    使用连接池 连接redis库的    Redis
'''

# 创建pool
pool = ConnectionPool(host='localhost', port=6379, db=0, decode_responses=True)
# 传入pool
db = Redis(connection_pool=pool)
# 下方是获取操作结果
resu = db.hget('mark', "name")
resu2 = db.hmget('mark', 'name', "age", "h")
resu3 = db.hgetall("mark")
# 下方是输出操作结果
print(resu, type(resu), sep=" 类型是: ")
print(resu2, type(resu2), sep=" 类型是: ")
print(resu3, type(resu3), sep=" 类型是: ")

from redis import ConnectionPool
from redis import StrictRedis

'''
    使用连接池连接 redis库的    StrictRedis
'''

pool = ConnectionPool(host="localhost", port=6379, db=0, decode_responses=True)
db = StrictRedis(connection_pool=pool)

本文地址:https://blog.csdn.net/MarkAdc/article/details/107068044

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网