python操作redis

操作单redis

需要安装redis模块:pip install redis

demo:

python 复制代码
#!/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:

python 复制代码
#!/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()
p.subscribe("aaa")
for m in p.listen():
    print(m)
    p.unsubscribe()

运行结果:

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

相关推荐
微风粼粼23 分钟前
程序员在线接单
java·jvm·后端·python·eclipse·tomcat·dubbo
云天徽上38 分钟前
【PaddleOCR】OCR表格识别数据集介绍,包含PubTabNet、好未来表格识别、WTW中文场景表格等数据,持续更新中......
python·ocr·文字识别·表格识别·paddleocr·pp-ocrv5
你怎么知道我是队长1 小时前
python-input内置函数
开发语言·python
叹一曲当时只道是寻常1 小时前
Python实现优雅的目录结构打印工具
python
hbwhmama2 小时前
python高级变量XIII
python
费弗里3 小时前
Python全栈应用开发利器Dash 3.x新版本介绍(3)
python·dash
dme.3 小时前
Javascript之DOM操作
开发语言·javascript·爬虫·python·ecmascript
加油吧zkf3 小时前
AI大模型如何重塑软件开发流程?——结合目标检测的深度实践与代码示例
开发语言·图像处理·人工智能·python·yolo
t_hj3 小时前
python规划
python
czhc11400756633 小时前
Linux 76 rsync
linux·运维·python