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'}
相关推荐
2301_8223754418 分钟前
Python虚拟环境(venv)完全指南:隔离项目依赖
jvm·数据库·python
2301_7903009618 分钟前
Python类型提示(Type Hints)详解
jvm·数据库·python
Eric.Lee202124 分钟前
SLAM 路径规划的安全走廊实现
python·机器人·ros·路径规划·避障·安全走廊
小W与影刀RPA31 分钟前
【影刀RPA】:智能过滤敏感词,高效输出表格
大数据·人工智能·python·低代码·自动化·rpa·影刀rpa
Yorlen_Zhang36 分钟前
python Tkinter Frame 深度解析与实战指南
开发语言·python
2401_8384725137 分钟前
Python多线程与多进程:如何选择?(GIL全局解释器锁详解)
jvm·数据库·python
2301_822363601 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
叫我辉哥e11 小时前
新手进阶Python:办公看板升级交互式可视化+移动端适配+多终端同步
开发语言·python
m0_561359671 小时前
Python面向对象编程(OOP)终极指南
jvm·数据库·python
zhangfeng11331 小时前
deepseek部署和训练的PyTorch CUDA Transformers Accelerate PEFT稳定版本呢推荐
人工智能·pytorch·python