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

相关推荐
0思必得0几秒前
[Web自动化] Selenium执行JavaScript语句
前端·javascript·爬虫·python·selenium·自动化
焱童鞋4 分钟前
解决 MeteoInfoLab 3.9.11 中 contourfm 导致的 ArrayIndexOutOfBoundsException
开发语言·python
封奚泽优9 分钟前
化学配对记忆游戏:用Python和Pygame打造趣味化学学习工具
python·pygame
梦幻精灵_cq15 分钟前
问题切入『视角很重要』——ansi-color有效编码序列“单背景判定”小部件的“简洁精妙”
python
有代理ip16 分钟前
成功请求的密码:HTTP 2 开头响应码深度解析
java·大数据·python·算法·php
0思必得017 分钟前
[Web自动化] Selenium截图
前端·爬虫·python·selenium·自动化
放飞自我的Coder1 小时前
【PDF拆分 Python拆分左右并排PDF】
python·pdf
nimadan121 小时前
**AI漫剧爆款生成器2025推荐,解锁高互动率与平台适配的
人工智能·python