redis基本操作 Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

'''
pip install redis

redis 可以看成内存中的大字典

redis五大数据类型 --> 指的是第一层的value值的类型
    - 字符串       "k1"
    - 列表        [11,22,33,11]
    - 集合        {11,22,33}
    - 字典        {
                    'kk1':vv1,
                    'kk2':vv2,
                    'kk3':{}  这个value不能是字典,如果有需要,则需要转换成字符串的形式。
                }
    - 有序集合      {('alex',4),('standby',3),('egon',9)}
'''


import redis

conn = redis.Redis(host='10.0.0.2',port=6379)

# 字符串
conn.set('k1','v1',ex=10)
conn.get('k1')


# 列表
# 可以当消息队列来使用
conn.lpush('users','alex')
conn.rpush('users','eric')
conn.lpop('users')
conn.rpop('users')

# 双向队列,可以hang住,可以模拟栈和队列,  爬虫,爬网页-广度优先和深度优先
conn.blpop('users',timeout=10)
conn.brpop('users',timeout=10)

conn.expire('key','超时时间')


count = conn.llen('users')
print(count)

vals = conn.lrange('users',0,10)
print(vals)


# redis针对列表类型,没有提供 iter 方法,需要自己实现
def list_scan_iter(key):
    # count = conn.llen(key)
    start = 0
    step = 3
    while True:
        vals = conn.lrange(key,start,start+step)
        start = start + step + 1
        if not vals:
            return
        for val in vals:
            yield val

result = list_scan_iter('users')
for item in result:
    print(item)



# 集合


# 哈希


# 有序结合

  

参考:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

猜你喜欢

转载自www.cnblogs.com/standby/p/9193210.html