python操作redis

操作单redis

需要安装redis模块:pip install redis

demo:

#!/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:

#!/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(node=nodes[0])
p.subscribe("aaa")
for m in p.listen():
    print(m)
    p.unsubscribe()

运行结果:

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

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值