码迷,mamicode.com
首页 > 编程语言 > 详细

Python操作redis

时间:2018-08-05 14:17:32      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:ebs   get   for   exe   pubsub   member   site   members   import   

安装python-redis

pip install redis

 

python操作redis

#从redis包中导入Redis类
from redis import Redis

#初始化redis实例
cache = Redis(host=‘10.2.2.120‘, port=‘6379‘)

#操作字符串
cache.set(‘username‘, ‘abc‘)
cache.delete(‘username‘)

#列表操作
cache.lpush(‘books‘, ‘java‘)
cache.lpush(‘books‘, ‘python‘)
cache.lpush(‘books‘, ‘php‘)
print(cache.lrange(‘books‘, 0, -1))

#集合的操作
cache.sadd(‘team‘, ‘blue‘)
cache.sadd(‘team‘, ‘yellow‘)
cache.sadd(‘team‘, ‘red‘)
print(cache.smembers(‘team‘))

#哈希的操作
cache.hset(‘website‘, ‘baidu‘, ‘www.baidu.com‘)
cache.hset(‘website‘, ‘google‘, ‘www.google.com‘)
print(cache.hgetall(‘website‘))

#事务的操作
pip = cache.pipeline()
pip.set(‘usernmae‘, ‘heboan‘)
pip.set(‘password‘, ‘123456‘)
pip.execute()

#发布与订阅(发布订阅要在不同的文件)

#订阅消息
ps = cache.pubsub()
ps.subscribe(‘email‘)
while True:
    for item in ps.listen():
        print(item)
        
#发布消息
for x in range(3):
    cache.publish(‘email‘, ‘xxxx@qq.com‘)
    

这里只是列出了一些基本的操作,其实和命令行是一样的

Python操作redis

标签:ebs   get   for   exe   pubsub   member   site   members   import   

原文地址:https://www.cnblogs.com/sellsa/p/9425214.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!