Python操作redis

安装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')
    

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

posted @ 2018-08-05 13:01  sellsa  阅读(433)  评论(0编辑  收藏  举报