python操作redis

文章介绍了如何在Python中安装和使用Redis模块,包括单机Redis的连接、设置和删除操作,以及使用RedisCluster进行集群操作,包括订阅/发布功能的演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

操作单redis

需要安装redis模块:pip install redis

demo:

#!/usr/bin/env python3
# coding = utf-8

import redis
import threading


def a():
    conn = redis.Redis(host="192.168.1.66", port=6379, password="123456", db=6,
                       # decode_responses=True  # 设置True存取数据编解码为字符串,默认False
                       )
    set_result = conn.set("a", "ABC")
    print("set_result:", set_result)
    getval = conn.get("a")
    print("getval=", getval)
    del_result = conn.delete("a")
    print("del_result:", del_result)

    def sub_th():
        sub = conn.pubsub()
        sub.subscribe("mych")
        for m in sub.listen():
            # 第一个消息type=subscribe是订阅确认消息
            print(m)

    t1 = threading.Thread(target=sub_th)
    t1.start()
    conn.publish("mych", "hello world")


def b():
    pool = redis.ConnectionPool(host="192.168.1.66", port=6379, password="123456", db=6,
                                max_connections=10, socket_timeout=10, socket_connect_timeout=5,
                                retry_on_timeout=True, health_check_interval=30, decode_responses=True)
    conn = redis.Redis(connection_pool=pool)
    conn.publish("mych", "test")
    conn.set("a", "AAA")
    val = conn.get("a")
    print(val)  # 字符串
    conn.delete("a")


a()
b()

 运行结果:

操作redis集群

需要安装redis-py-cluster模块:pip install redis-py-cluster

集群192.168.1.66,端口9001-9006

demo:

#!/usr/bin/env python3
# coding = utf-8

from rediscluster import RedisCluster

nodes = [
    {"host": "192.168.1.66", "port": "9001"},
    {"host": "192.168.1.66", "port": "9002"}
]
rc = RedisCluster(startup_nodes=nodes, decode_responses=True, password="123456")
rc.set("a", "AAA")
v = rc.get("a")
print("v=", v)
rc.delete("a")
rc.publish("abc", "hello a")
p = rc.pubsub(node=nodes[0])
p.subscribe("aaa")
for m in p.listen():
    print(m)
    p.unsubscribe()

运行结果:

 可以设置decode_responses=True,自动解码为字符串,默认False字节串;订阅和取消订阅也会listen到确认消息;

### Python 操作 Redis 使用指南 #### 1. 安装 `redis-py` 库 在使用 Python 操作 Redis 之前,需要安装官方推荐的 `redis-py` 库。可以通过 pip 工具完成安装: ```bash pip install redis ``` --- #### 2. 连接到 Redis 服务器 为了与 Redis 交互,首先需要建立连接。以下是一个简单的连接示例: ```python import redis # 创建 Redis 连接对象 r = redis.Redis(host='localhost', port=6379, db=0) # 测试连接是否正常 if r.ping(): print("成功连接到 Redis 服务器") else: print("无法连接到 Redis 服务器") ``` 此代码片段展示了如何通过指定主机名、端口和数据库编号来初始化 Redis 对象,并验证连接的有效性[^3]。 --- #### 3. 存储和获取字符串数据 Redis 支持基本的键值对存储操作。下面演示了如何设置和读取字符串类型的键值对: ```python # 设置键值对 r.set('name', 'Alice') # 获取键对应的值 value = r.get('name') print(f"Key 'name' 的值为: {value.decode()}") # 输出 Alice ``` 注意:Redis 返回的值是以字节形式存在的,因此通常需要用 `.decode()` 方法转换成字符串[^1]。 --- #### 4. 处理二进制数据 除了普通的字符串外,Redis 还能够存储任意的二进制数据。例如,可以将图片或其他文件的内容保存至 Redis 并稍后检索出来: ```python # 假设 binary_data 是一段二进制数据 binary_data = b'\x89PNG\r\n\x1a\n\x00\x00\x00' # 将二进制数据存入 Redis r.set('image_key', binary_data) # 从 Redis 中取出二进制数据 retrieved_binary = r.get('image_key') print(retrieved_binary) # 输出原始二进制流 ``` 这里的关键在于无需特殊编码即可直接传递二进制内容给 Redis[^2]。 --- #### 5. 使用有序集合(Sorted Set) Redis 提供了一种名为 Sorted Set 的高级数据结构,其中每个成员都关联着一个分数用于排序。下面是关于如何向有序集中添加元素以及查询排名的例子: ```python # 添加带有权重的项目到 sorted set r.zadd('leaderboard', {'user1': 150, 'user2': 300}) # 查询特定用户的得分情况 score_user1 = r.zscore('leaderboard', 'user1') print(f"user1 得分为: {score_user1}") # 获取排行榜前两名 top_users = r.zrange('leaderboard', 0, 1, desc=True, withscores=True) for user, score in top_users: print(f"{user.decode()}: {score}") ``` 上述脚本先定义了一个叫 leaderboard 的有序集,接着插入两个用户及其对应积分最后打印出最高分者的信息[^3]。 --- #### 6. 错误处理机制 当尝试访问不存在的服务或者网络中断等情况发生时,应该合理捕获可能出现的各种异常状况以免程序崩溃。如下所示提供了一套完善的错误捕捉方案: ```python def create_redis_connection(host='localhost', port=6379, db=0): """安全地创建 Redis 链接""" try: conn = redis.Redis(host=host, port=port, db=db) if not conn.ping(): raise Exception("Ping failed") return conn except redis.ConnectionError as ce: print(f"未能建立链接: {ce}") except redis.TimeoutError as te: print(f"超时错误: {te}") except Exception as e: print(f"未知错误: {e}") connection = create_redis_connection() if connection is None: exit(-1) ``` 这段函数封装了常见的几种异常情形以便于调用方更方便地管理和响应不同种类的问题[^4]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值