Python使用redis
title: Python使用redis
date: 2022-02-06 16:42:53
categories: 开发
tags: [redis,数据库,Python]
安装Redis模块
Python无内置redis工具,需先安装redis模块:
pip3 install redis
连接数据库
import redis
r = redis.StrictRedis(host='localhost', port=6379, decode_responses=True)
r.set('name', 'Lihua')
print(r['name'])
print(r.get('name')
redis 提供两个类 Redis 和 StrictRedis, StrictRedis 用于实现大部分官方的命令,Redis 是 StrictRedis 的子类,用于向后兼用旧版本。
redis 取出的结果默认是字节,可以设定 decode_responses=True 改成字符串。
连接池
redis-py 使用 connection pool 来管理对一个 redis server 的所有连接,避免每次建立、释放连接的开销。
默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数 Redis,这样就可以实现多个 Redis 实例共享一个连接池。
import redis
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
String操作
TODO……
List操作
TODO……
Set操作……
TODO……