redis 管道

redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,

如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,

并且默认情况下一次pipline 是原子性操作。

import redis
 
pool = redis.ConnectionPool(host='10.211.55.4', port=6379)
 
r = redis.Redis(connection_pool=pool)
 
# pipe = r.pipeline(transaction=False)
pipe = r.pipeline(transaction=True)
pipe.multi()
pipe.set('name', 'alex')
pipe.set('role', 'sb')
 
pipe.execute()

own:

# 管道 如果想要在一次请求中指定多个命令
import redis

# 1.创建一个redis连接池
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)

# 2.每个Redis实例都会维护一个自己的连接池。
r = redis.Redis(connection_pool=pool)

# 创建一个管道
pipe = r.pipeline(transaction=True)

# 可以执行多个指定
pipe.multi()

# 在pip中设置值
pipe.set('name','riven')
pipe.set('role','mark')


# 执行pip
pipe.execute()

实现计数器

# 管道 如果想要在一次请求中指定多个命令
import redis

# 1.创建一个redis连接池
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)

# 2.每个Redis实例都会维护一个自己的连接池。
r = redis.Redis(connection_pool=pool)

r.set('count', 1000)


with r.pipeline() as pipe:

    # 先监视,自己的值没有被修改过
    r.watch('count')

    # 事务开始
    pipe.multi()

    # 取到开始设置的值count
    old_count = r.get('count')

    # 将 count变成数字
    count = int(old_count)
    if count > 0:  # 有库存
        pipe.set('count',count - 1)

    # 执行,把所有命令一次性推送过去
    pipe.execute()

发布订阅

发布者:服务器

订阅者:Dashboad和数据处理

Demo如下:

import redis


class RedisHelper:

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

    def public(self, msg):
        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

订阅者:

from Reade_test.RedisHelper_file import RedisHelper

# 订阅者
#   实例化一个类
obj = RedisHelper()

# 调用 subscribe 拿到发布者发送的信息
redis_sub = obj.subscribe()

# 循环获取发送者的值
while True:
    # parse_response “解析来自发布/订阅命令的响应”
    msg = redis_sub.parse_response()
    # 打印发布者的信息
    print(msg)

发布者:

# 发布者
from Reade_test.RedisHelper_file import RedisHelper
obj = RedisHelper()

obj.public('mark')

猜你喜欢

转载自www.cnblogs.com/Rivend/p/12021885.html
今日推荐