Python中连接Redis数据库并存储数据
在 Python 中,可以使用 redis 库连接 Redis 数据库并存储数据。以下是一个完整的示例,展示如何连接 Redis、存储数据以及读取数据。
安装依赖
首先,确保安装了 redis Python 库。如果尚未安装,可以运行以下命令:
bash
pip install redis
示例代码
python
import redis
# 连接 Redis 数据库
def connect_to_redis():
try:
# 创建 Redis 客户端
redis_client = redis.StrictRedis(
host='localhost', # Redis 服务器地址
port=6379, # Redis 端口号
password=None, # 如果 Redis 设置了密码,则在此填写
decode_responses=True # 自动解码为字符串
)
# 测试连接
redis_client.ping()
print("Connected to Redis successfully!")
return redis_client
except redis.ConnectionError as e:
print(f"Redis connection error: {e}")
return None
# 存储数据到 Redis
def store_data(redis_client, key, value):
try:
redis_client.set(key, value)
print(f"Data stored successfully: {key} -> {value}")
except Exception as e:
print(f"Error storing data: {e}")
# 读取数据
def get_data(redis_client, key):
try:
value = redis_client.get(key)
print(f"Data retrieved: {key} -> {value}")
return value
except Exception as e:
print(f"Error retrieving data: {e}")
return None
if __name__ == "__main__":
# 连接到 Redis
redis_client = connect_to_redis()
if redis_client:
# 存储数据
store_data(redis_client, "key1", "value1")
store_data(redis_client, "key2", "value2")
# 读取数据
get_data(redis_client, "key1")
get_data(redis_client, "key2")
代码说明
-
连接 Redis:
- 使用
redis.StrictRedis创建 Redis 客户端。 - 参数说明:
host:Redis 服务器地址,默认为localhost。port:Redis 端口号,默认为6379。password:如果 Redis 设置了密码,则需要提供密码。decode_responses:设置为True,自动将 Redis 返回的字节数据解码为字符串。
- 使用
-
存储数据:
- 使用
set(key, value)方法将数据存储到 Redis 中。 key是键,value是值。
- 使用
-
读取数据:
- 使用
get(key)方法从 Redis 中读取数据。 - 如果键不存在,返回
None。
- 使用
-
异常处理:
- 捕获连接错误和操作错误,确保程序不会因异常崩溃。
运行结果
运行上述代码后,输出如下:
Connected to Redis successfully!
Data stored successfully: key1 -> value1
Data stored successfully: key2 -> value2
Data retrieved: key1 -> value1
Data retrieved: key2 -> value2
扩展:存储字典数据
如果需要存储字典数据,可以使用 Redis 的 hset 方法(哈希存储):
python
# 存储字典数据
def store_dict(redis_client, key, data_dict):
try:
redis_client.hset(key, mapping=data_dict)
print(f"Dictionary stored successfully: {key} -> {data_dict}")
except Exception as e:
print(f"Error storing dictionary: {e}")
# 读取字典数据
def get_dict(redis_client, key):
try:
data_dict = redis_client.hgetall(key)
print(f"Dictionary retrieved: {key} -> {data_dict}")
return data_dict
except Exception as e:
print(f"Error retrieving dictionary: {e}")
return None
# 示例
if __name__ == "__main__":
redis_client = connect_to_redis()
if redis_client:
# 存储字典
data = {"field1": "value1", "field2": "value2"}
store_dict(redis_client, "my_dict", data)
# 读取字典
get_dict(redis_client, "my_dict")
运行结果
Connected to Redis successfully!
Dictionary stored successfully: my_dict -> {'field1': 'value1', 'field2': 'value2'}
Dictionary retrieved: my_dict -> {'field1': 'value1', 'field2': 'value2'}
通过以上代码,你可以轻松实现 Redis 的连接、数据存储和读取操作。
以下是完整的Python代码示例;
python
import redis
# 连接 Redis 数据库
def connect_to_redis():
try:
# 创建 Redis 客户端
redis_client = redis.StrictRedis(
host='localhost', # Redis 服务器地址
port=7001, # Redis 端口号,可以根据自己的Redis数据库自行更改配置,默认端口号是6379
password='123456', # 如果 Redis 设置了密码,则在此填写
decode_responses=True # 自动解码为字符串
)
# 测试连接
redis_client.ping()
print("Connected to Redis successfuly!")
return redis_client
except redis.ConnectionError as e:
print(f"Redis connection error: {e}")
return None
# 存储数据到 redis
def store_data(redis_client, key, value):
try:
redis_client.set(key, value)
print(f"Data stored successfully: {key} -> {value}")
except Exception as e:
print(f"Error storing data: {e}")
# 读取数据
def get_data(redis_client, key):
try:
value = redis_client.get(key)
print(f"Data retrieved: {key} -> {value}")
return value
except Exception as e:
print(f"Error retriving data: {e}")
return None
# 存储字典数据
# 如果需要存储字典数据,可以使用 Redis 的 hset 方法(哈希存储):
def store_dict_data(redis_client, key, data_dict):
try:
redis_client.hset(key, mapping=data_dict)
print(f"Dictionary stored successfully: {key} -> {data_dict}")
except Exception as e:
print(f"Error retrieved: {key} -> {data_dict}")
# 读取字典数据
def get_data_dict(redis_client, key):
try:
data_dict = redis_client.hgetall(key)
print(f"Dictionary retrieved: {key} -> {data_dict}")
return data_dict
except Exception as e:
print(f"Error retrievng dictionary: {e}")
return None
# 主函数
if __name__ == "__main__":
# 连接到 Redis
redis_client = connect_to_redis()
if redis_client:
# 存储数据
store_data(redis_client, "key1", "value1")
store_data(redis_client, "key2", "value2")
# 读取数据
val1 = get_data(redis_client, "key1")
print(f"key1: {val1}")
val2 = get_data(redis_client, "key2")
print(f"key2: {val2}")
# 存储字典
data_dict = {"field1": "val1", "field2": "val2"}
store_dict_data(redis_client, "my_dict", data_dict)
# 读取字典
data_dict_2 = get_data_dict(redis_client, "my_dict")
print(data_dict_2)
运行结果如下:
bash
$ python myRedisExample.py
Connected to Redis successfuly!
Data stored successfully: key1 -> value1
Data stored successfully: key2 -> value2
Data retrieved: key1 -> value1
key1: value1
Data retrieved: key2 -> value2
key2: value2
Dictionary stored successfully: my_dict -> {'field1': 'val1', 'field2': 'val2'}
Dictionary retrieved: my_dict -> {'field1': 'val1', 'field2': 'val2'}
{'field1': 'val1', 'field2': 'val2'}