安装Redis
brew install redis
开启、关闭Redis
# 开启服务
brew services start redis
# 关闭服务
brew services stop redis
redis数据结构
Redis 支持多种数据结构,包括字符串、哈希、列表、集合和有序集合。每种数据结构都有其特定的命令和用法。以下是一个简单的类图,展示了 Redis 的基本数据结构:
redis-cli操作
% redis-cli ping
PONG
% redis-cli
127.0.0.1:6379> set name peter
OK
127.0.0.1:6379> get name
"peter"
127.0.0.1:6379> keys *
1) "name"
安装redis-py
Redis是一种开源的内存数据结构存储,用作数据库、缓存和消息代理。redis-py是一个Python客户端库,允许Python程序与Redis进行交互。安装包如下:
pip install redis
数据库连接和释放
要连接到Redis数据库,需要提供Redis服务器的主机地址和端口。
import redis
def create_connection(host='localhost', port=6379, db=0):
connection = None
try:
connection = redis.Redis(host=host, port=port, db=db)
if connection.ping():
print("Connection to Redis DB successful")
except redis.ConnectionError as e:
print(f"The error '{e}' occurred")
return connection
def close_connection(connection):
# Redis-py does not require explicit close
print("Redis connection does not need to be closed explicitly")
# 使用示例
connection = create_connection()
close_connection(connection)
增删改查
在连接到数据库后,可以执行基本的Redis操作,如插入、查询、更新和删除数据。
插入数据
def insert_data(connection, key, value):
try:
connection.set(key, value)
print(f"Data inserted: {key} -> {value}")
except redis.RedisError as e:
print(f"The error '{e}' occurred")
insert_data(connection, 'name', 'Alice')
查询数据
def query_data(connection, key):
try:
value = connection.get(key)
if value:
print(f"Data retrieved: {key} -> {value.decode('utf-8')}")
else:
print(f"No data found for key: {key}")
except redis.RedisError as e:
print(f"The error '{e}' occurred")
query_data(connection, 'name')
更新数据
Redis中的set命令不仅用于插入数据,也可用于更新数据。
def update_data(connection, key, value):
try:
connection.set(key, value)
print(f"Data updated: {key} -> {value}")
except redis.RedisError as e:
print(f"The error '{e}' occurred")
update_data(connection, 'name', 'Bob')
删除数据
def delete_data(connection, key):
try:
result = connection.delete(key)
if result:
print(f"Data deleted for key: {key}")
else:
print(f"No data found for key: {key}")
except redis.RedisError as e:
print(f"The error '{e}' occurred")
delete_data(connection, 'name')
异常处理
处理异常是确保程序稳定性的重要部分。在上述代码中,已通过try-except块来处理可能的异常。此外,还可以进一步细化异常处理逻辑。
def create_connection(host='localhost', port=6379, db=0):
connection = None
try:
connection = redis.Redis(host=host, port=port, db=db)
if connection.ping():
print("Connection to Redis DB successful")
except redis.ConnectionError as e:
print("Failed to connect to Redis server")
except redis.RedisError as e:
print(f"Redis error: {e}")
return connection
Redis凭借其高性能和丰富的数据结构,已成为缓存、实时数据分析和消息代理等应用场景的理想选择。掌握Python与Redis的交互,将极大提高在数据处理和应用开发中的效率。
相关链接
https://github.com/redis/redis-pyhttps://redis-py.readthedocs.io/en/stable/https://www.runoob.com/w3cnote/python-redis-intro.html