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

相关推荐
aini_lovee2 小时前
python在容器内克隆拉取git私有仓库
git·python·elasticsearch
安全系统学习4 小时前
网络安全之RCE简单分析
开发语言·python·算法·安全·web安全
蹦蹦跳跳真可爱5896 小时前
Python----神经网络发(神经网络发展历程)
人工智能·python·深度学习·神经网络·计算机视觉
chao_7896 小时前
标注工具核心代码解析——class AnnotationVie【canvas.py]
开发语言·python·qt5
在未来等你6 小时前
SQL进阶之旅 Day 29:NoSQL结合使用策略
redis·sql·mongodb·elasticsearch·postgresql·nosql·hybrid-database
struggle20257 小时前
tvm开源程序是适用于 CPU、GPU 和专用加速器的开放式深度学习编译器堆栈
人工智能·python·深度学习
仟濹7 小时前
「pandas 与 numpy」数据分析与处理全流程【数据分析全栈攻略:爬虫+处理+可视化+报告】
大数据·python·数据分析·numpy·pandas
测试杂货铺7 小时前
postman接口测试
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
四川兔兔7 小时前
pytorch 之 nn 库与调试
人工智能·pytorch·python
終不似少年遊*8 小时前
机器学习方法实现数独矩阵识别器
人工智能·python·opencv·机器学习·计算机视觉·矩阵