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'}
相关推荐
笨鸟先飞,勤能补拙3 小时前
AI 赋能网络安全:技术全景、成熟度评估与实战案例
人工智能·python·安全·web安全·网络安全·sqlite·github
长和信泰光伏储能4 小时前
京津冀光伏发电:绿色能源的未来之路
python·能源
浦信仿真大讲堂4 小时前
从重复操作到自动化闭环:如何让 CST 与 Python 真正协同起来
python·自动化·cst·仿真软件·达索软件
Gu Gu Study5 小时前
ScoutLoop开放域深度研究引擎(agent的初步设计想法)
人工智能·python
卷无止境5 小时前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境6 小时前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python
lpfasd1236 小时前
MediaCrawler 项目深度分析
chrome·python·chrome devtools
Dxy12393102166 小时前
Python项目打包成EXE完整教程(PyInstaller实战避坑)
开发语言·python
bamb007 小时前
一个项目带你入门AI应用开发01
python
独行侠影a7 小时前
APScheduler+Redis 分布式定时任务:解决多实例任务重复执行
数据库·redis·分布式