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到确认消息;

相关推荐
陈天伟教授4 小时前
人工智能训练师认证教程(2)Python os入门教程
前端·数据库·python
2301_764441334 小时前
Aella Science Dataset Explorer 部署教程笔记
笔记·python·全文检索
爱笑的眼睛114 小时前
GraphQL:从数据查询到应用架构的范式演进
java·人工智能·python·ai
BoBoZz194 小时前
ExtractSelection 选择和提取数据集中的特定点,以及如何反转该选择
python·vtk·图形渲染·图形处理
liwulin05065 小时前
【PYTHON-YOLOV8N】如何自定义数据集
开发语言·python·yolo
木头左5 小时前
LSTM量化交易策略中时间序列预测的关键输入参数分析与Python实现
人工智能·python·lstm
电子硬件笔记5 小时前
Python语言编程导论第七章 数据结构
开发语言·数据结构·python
HyperAI超神经6 小时前
【vLLM 学习】Prithvi Geospatial Mae
人工智能·python·深度学习·学习·大语言模型·gpu·vllm
逻极6 小时前
Python MySQL防SQL注入实战:从字符串拼接的坑到参数化查询的救赎
python·mysql·安全·sql注入
赫凯6 小时前
【强化学习】第一章 强化学习初探
人工智能·python·强化学习