这篇文章主要讲解了python实现与redis交互的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。
import redis
pool= redis.ConnectionPool(host='localhost',port=6379,decode_responses=True)
r=redis.Redis(connection_pool=pool)
r2=redis.Redis(connection_pool=pool)
r.set('apple','a')
print(r.get('apple'))
r2.set('banana','b')
print(r.get('banana'))
print(r.client_list())
print(r2.client_list())#可以看出两个连接的id是一致的,说明是一个客户端连接
如果想要了解更多redis命令,可以参考我的另外一篇博文:
import redis
r=redis.Redis(host='localhost',port=6379,decode_responses=True)
# r=redis.StrictRedis(host='localhost',port=6379)
r.set('key','value')
value=r.get('key')
# print(type(value))
print(value)
r.hset('info','name','lilei')
r.hset('info','age','18')
print(r.hgetall('info'))
r.sadd('course','math','english','chinese')
print(r.smembers('course'))
一般情况下,执行一条命令后必须等待结果才能输入下一次命令,管道用于在一次请求中执行多个命令。
import redis,time
r=redis.Redis(host="localhost",port=6379,decode_responses=True)
pipe=r.pipeline(transaction=True)
pipe.set('p1','v2')
pipe.set('p2','v3')
pipe.set('p3','v4')
time.sleep(5)
pipe.execute()
python中可以使用管道来代替事务:
import redis,time
import redis.exceptions
r=redis.Redis(host='localhost',port=6379,decode_responses=True)
pipe=r.pipeline()
print(r.get('a'))
try:
# pipe.watch('a')
pipe.multi()
pipe.set('here', 'there')
pipe.set('here1', 'there1')
pipe.set('here2', 'there2')
time.sleep(5)
pipe.execute()
except redis.exceptions.WatchError as e:
print("Error")
import redis
r=redis.Redis(host="localhost",port=6379,decode_responses=True)
#发布使用publish(self, channel, message):Publish ``message`` on ``channel``.
Flag=True
while Flag:
msg=input("主播请讲话>>:")
if len(msg)==0:
continue
elif msg=='quit':
break
else:
r.publish('cctv0',msg)
import redis
r=redis.Redis(host="localhost",port=6379,decode_responses=True)
#发布使用publish(self, channel, message):Publish ``message`` on ``channel``.
Flag=True
chan=r.pubsub()#返回一个发布/订阅对象
msg_reciver=chan.subscribe('cctv0')#订阅
msg=chan.parse_response()#第一次会返回订阅确认信息
print(msg)
print("订阅成功,开始接收------")
while Flag:
msg=chan.parse_response()#接收消息
print(">>:",msg[2])#此处的信息格式['消息类型', '频道', '消息'],所以使用[2]来获取
看完上述内容,是不是对python实现与redis交互的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。