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

相关推荐
站大爷IP3 小时前
Python operator模块的methodcaller:一行代码搞定对象方法调用的黑科技
python
GarrettGao5 小时前
Frida常见用法
javascript·python·逆向
Juchecar6 小时前
Pandas技巧:利用 category 类型节省内存
python
阿杆6 小时前
为什么我建议你把自建 Redis 迁移到云上进行托管
redis·后端
间彧6 小时前
什么是Redis分布式锁,有何使用场景
redis
跟橙姐学代码7 小时前
Python时间处理秘籍:别再让日期时间卡住你的代码了!
前端·python·ipython
mortimer9 小时前
Python 文件上传:一个简单却易犯的错误及解决方案
人工智能·python
Juchecar9 小时前
NumPy编程:鼓励避免 for 循环
python
间彧10 小时前
Spring Boot项目中,Redis 如何同时执行多条命令
java·redis
Java陈序员10 小时前
直播录制神器!一款多平台直播流自动录制客户端!
python·docker·ffmpeg