Redis管道和发布订阅

管道:原子性执行命令

'''
redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,
如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,
并且默认情况下一次pipline 是原子性操作
'''
import redis

pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)

# pipe = r.pipeline(transaction=False)
pipe = r.pipeline(transaction=True)
# 这两条一起执行
pipe.set('name', 'zhangsan')
pipe.set('role', 'student')

pipe.execute()

发布订阅:仅在Redis内部使用的

要调用的类:RedisHelper

class RedisHelper:

    def __init__(self):
        self.__conn = redis.Redis(host='127.0.0.1')
        self.chan_sub = 'fm104.5'
        self.chan_pub = 'fm104.5'

    def public(self, msg): # 调redis的publish方法发消息
        self.__conn.publish(self.chan_pub, msg)
        return True

    def subscribe(self):
        # 开始订阅,相当于‘打开收音机’
        pub = self.__conn.pubsub()
        # 调频道
        pub.subscribe(self.chan_sub)
        # 准备接收消息,再调一下才开始真正的接收
        pub.parse_response()
        return pub

发布者:

import RedisHelper
 
obj = RedisHelper()
obj.public('hello')

订阅者:

import RedisHelper

obj = RedisHelper()
redis_sub = obj.subscribe()

while True:
    # 再调一次才开始收,没有就阻塞
    msg = redis_sub.parse_response()
    print(msg)

猜你喜欢

转载自www.cnblogs.com/staff/p/9955868.html