Python中连接Redis数据库并存储数据

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")

代码说明

  1. 连接 Redis

    • 使用 redis.StrictRedis 创建 Redis 客户端。
    • 参数说明:
      • host:Redis 服务器地址,默认为 localhost
      • port:Redis 端口号,默认为 6379
      • password:如果 Redis 设置了密码,则需要提供密码。
      • decode_responses:设置为 True,自动将 Redis 返回的字节数据解码为字符串。
  2. 存储数据

    • 使用 set(key, value) 方法将数据存储到 Redis 中。
    • key 是键,value 是值。
  3. 读取数据

    • 使用 get(key) 方法从 Redis 中读取数据。
    • 如果键不存在,返回 None
  4. 异常处理

    • 捕获连接错误和操作错误,确保程序不会因异常崩溃。

运行结果

运行上述代码后,输出如下:

复制代码
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'}
相关推荐
vyuvyucd2 小时前
Python虚拟环境终极指南:venv到uv进阶
开发语言·python·uv
老兵发新帖2 小时前
基于Label Studio的视频标注与YOLO模型训练全流程指南
python·yolo·音视频
Codeking__2 小时前
Redis的value类型及编码方式介绍——string
数据库·redis·缓存
进阶的鱼2 小时前
一文助你了解Langchain
python·langchain·agent
收菜福星2 小时前
智能体来了:从 Python 开发者视角深度剖析与实践
python
佑白雪乐2 小时前
<Python第1集>
开发语言·python
liu****2 小时前
git工具
git·python·算法·机器学习·计算机基础
rgeshfgreh2 小时前
2025年Python安装全指南
python
数据大魔方2 小时前
【期货量化进阶】期货Tick数据分析与应用:高频数据入门(TqSdk完整教程)
python·算法·数据挖掘·数据分析·github·程序员创富·期货程序化