一、其他常用操作
1、delete(*names)
# 根据删除redis中的任意数据类型
2、exists(name)
# 检测redis的name是否存在
3、keys(pattern='*')
# 根据模型获取redis的name
# 更多:
# KEYS * 匹配数据库中所有 key 。
# KEYS h?llo 匹配 hello , hallo 和 hxllo 等。
# KEYS h*llo 匹配 hllo 和 heeeeello 等。
# KEYS h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo
4、expire(name ,time)
# 为某个redis的某个name设置超时时间
5、rename(src, dst)
# 对redis的name重命名为
6、move(name, db))
# 将redis的某个值移动到指定的db下
注:redis的数据库一共有16个,分别是0-15,用redis命令操作的时候,用select db_index来切换数据库,如select 2
7、randomkey()
# 随机获取一个redis的name(不删除)
8、type(name)
# 获取name对应值的类型
9、scan(cursor=0, match=None, count=None)
正则匹配name
10、scan_iter(match=None, count=None)
# 同字符串操作,用于增量迭代获取key
更多redis的命令操作:猛击这里
二、管道
redis-py默认在执行每次请求都会创建(连接池申请连接)和断开(归还连接池)一次连接操作,如果想要在一次请求中指定多个命令,则可以使用pipline实现一次请求指定多个命令,并且默认情况下一次pipline 是原子性操作。
import redis
pool = redis.ConnectionPool(host='localhost', port=6379,db=2) #可以设置db
r = redis.Redis(connection_pool=pool)
# pipe = r.pipeline(transaction=False)
pipe = r.pipeline(transaction=True)
pipe.set('name', 'alex') #这边只是设置了,但是没有执行
pipe.set('role', 'sb')
pipe.execute() #当执行execute,才会批量去执行上面的命令
三、发布订阅
3.1、原理图
发布者:服务器 订阅者:Dashboad和数据处理
3.2、实现
1、RedisHelper
说明:对发布订阅进行封装
import redis
class RedisHelper(object):
def __init__(self):
self.__conn = redis.Redis(host="localhost")
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
2、订阅者:
from monitor.redis_helper import RedisHelper
obj = RedisHelper()
redis_sub = obj.subscribe()
while True:
msg = redis_sub.parse_response() #第2次准备接收动作
print(msg)
3、发布者:
from monitor.redis_helper import RedisHelper
obj = RedisHelper()
obj.public("hello world") #发布消息
3.3、redis命令订阅发布
1、发布
127.0.0.1:6379> help publish
PUBLISH channel message
summary: Post a message to a channel
since: 2.0.0
group: pubsub
127.0.0.1:6379> publish "fm104.5" helloword #publish 频道 消息
(integer) 1
2、订阅
127.0.0.1:6379> help subscribe
SUBSCRIBE channel [channel ...]
summary: Listen for messages published to the given channels
since: 2.0.0
group: pubsub
127.0.0.1:6379> subscribe "fm104.5" #subscribe 频道,可以订阅多个频道
Reading messages... (press Ctrl-C to quit)
1) "subscribe"
2) "fm104.5"
3) (integer) 1