python redis封装类
时间: 2023-11-06 09:00:54 浏览: 37
Python Redis库提供了一些封装类,用于与Redis数据库进行交互。这些封装类包括Redis、StrictRedis和ConnectionPool。其中,Redis类是StrictRedis类的子类,ConnectionPool类用于管理Redis连接池。
Redis类是StrictRedis类的子类,它提供了一些额外的功能,如事务和流水线。StrictRedis类是Redis库的主要类,它提供了对Redis数据库操作的各种方法,如设置键值对、获取键值对、列表和集合操作等。
ConnectionPool类用于管理Redis连接池,它提供了用于创建和释放连接的方法,并且可以设置最大连接数和超时时间等参数。
例子:
```python
import redis
# 创建Redis连接
r = redis.Redis(host='localhost', port=6379, db=0)
# 设置键值对
r.set('name', 'Alice')
# 获取键值对
name = r.get('name')
print(name) # 输出: b'Alice'
# 列表操作
r.lpush('fruits', 'apple', 'banana', 'orange')
fruits = r.lrange('fruits', 0, -1)
print(fruits) # 输出: [b'orange', b'banana', b'apple']
# 集合操作
r.sadd('colors', 'red', 'green', 'blue')
colors = r.smembers('colors')
print(colors) # 输出: {b'green', b'blue', b'red'}
# 释放连接
r.close()
```