3.6 Python操作Redis
from redis import StrictRedis,ConnectionPool
# 1.连接数据库
# 连接redis本地数据库,选择db1
redis0 = StrictRedis(host='localhost',port=6379,db=1)
# 使用ConnectionPool方法连接数据库,选择数据库db0
url = 'redis://:@localhost:6379/0'
pool = ConnectionPool.from_url(url)
redis1 = StrictRedis(connection_pool=pool)
# 2. 操作字符串 String
redis0.set('name_test_string','MarcoMei')
# 读取字符串key值
print(redis0.get('name_test_string'))
# 3. 操作列表List
# 尾部插入列表数据
redis0.rpush('score_test_list',1,2,3)
# 头部插入列表数据
redis0.lpush('score_test_list',4,5,6)
# 4. 操作集合Set
# 向名为tag_test_set的集合中添加多个内容:Book, Tea, Coffee
redis0.sadd('tag_test_set','Book','Tea','Coffee')
# 查看集合tag_test_set的内容
print(redis0.smembers('tag_test_set'))
# 5. 操作有序集合Sorted Set
redis0.zadd('grade_test_sorted',100,'Marco',99,'Kevin')
# 6. 操作哈希Hash:即是一个Hash表的键值对数据结构
# 添加一对一关系数据结构, cake: 5
redis0.hset('price_test_hash1', 'cake', 5)
redis0.hget('price_test_hash1','cake')
# 添加多个键值对的数据结构,
redis0.hmset('price_test_hash2', {'cake': 5,'price':20,'weight':'big','name':'for_marco'} )
用例

Last updated