python - 如何连接redis

先安装redis
python - 如何连接redis_第1张图片

第一种方式

conn = redis.Redis()
# conn = redis.Redis(host='localhost', port=6379) 可以不用指定,redis默认host='localhost', port=6379

conn.set('name', 'fentiao', 3)
# 3是失效时间

print(conn.get('name'))
print("等待3秒........")
time.sleep(3)

print(conn.get('name'))
# 等待3秒重新获取name对应的value时连接已经失效,返回None

python - 如何连接redis_第2张图片

第二种方式

# 为了减少每次建立连接, 释放连接的开销, 推荐使用连接池。
# 多个redis对象可以共用一个连接池。

pool = redis.ConnectionPool(host='localhost', port=6379)
conn = redis.Redis(connection_pool=pool)
conn.set('name', 'fentiao', 4)  # 4代表的是失效时间, 单位为秒
# 默认返回bytes类型, 如果转换, 需要解码为utf-8编码格式
print(conn.get('name').decode('utf-8'))
print("等待3秒........")
time.sleep(3)
print(conn.get('name')

python - 如何连接redis_第3张图片

你可能感兴趣的:(redis)