redis在python中的應用

努力奮鬥的小菲菲發表於2019-02-16

Redis常用的資料結構


  • string

最簡單的結構,key-value形式

  • list

一個key對應一個連結串列

  • hash:

記錄一個物件

  • set

無重複的資料集合

  • sorted set (zset)

有序無重複的資料集合

在python中的應用

redis會預設生成0-15的庫,推薦使用StrictRedis連線方式

import redis
pool = redis.ConnectionPool(host=`localhost`, port= 6379, db= 0)
client = redis.StrictRedis(connection_pool=pool)

統一操作

client.exists(key) #是否存在key
client.delete(key) #刪除key
client.type(key) #返回key型別
client.keys(pattern) #返回匹配pattern的key
client.randomkey() #隨機返回一個key
client.rename(key1, key2) #更改key1名字為key2
client.dbsize() #當前庫中key數量
client.expire(key, time) #設定key存在時間
client.ttl(key) #獲取key的存在時間
client.flushdb() #刪除當前庫中所有key
client.flushall() #刪除所有庫中的所有key

string型別操作

client.set(key, val)
client.get(key)
client.getset(key, val) #返回舊value
client.mget(key1, key2, ...) #返回多個key的val
client.setnx(key, value) #設定不存在的key
client.setex(key, time, value)
client.mset(key1, value1, key2, value2,...)#批量設定key,value
client.msetnx(key, value, key1,value1)
client.incr(key) # value + 1
client.incrby(key,integer) # value + integer
client.decr(key) # value - 1
client.decrby(key, integer) #value - integer
client.appent(key, value) #附加value
client.substr(key, start, end) #返回子串

list型別操作

client.rpush(key, value) #尾部新增
client.lpush(key, value) #頭部新增
client.llen(key) #長度
client.lrange(key, start, end) #
client.ltrim(key, start, end)
client.lindex(key, index)
client.lset(key, index, value)
client.lrem(key, count, value)
client.lpop(key)
client.rpop(key)
client.blpop(key1, key2, ...)
client.brpop(key1, key2, ...)
client.rpoplpush(srckey, dstkey)

set型別操作

client.sadd(key, value)
client.srem(key, value)
client.spop(key)
client.smove(skey, dkey, value)
client.scard(key)
client.sismember(key, member)
client.sinter(key1, key2,...)
client.sinterstore(dstkey, key1, key2, ...)
client.sunion(key1, key2, ...)
client.sunionstore(dstkey, key1, key2, ...)
client.sdiff(key1, key2, ...)
client.sdiffstore(dstkey, key1, key2, ...)
client.smembers(key)
client.srandmember(key)

zset型別操作

client.zadd(key, score, value)
client.zrem(key,value)
client.zincrby(key, increment, member)
client.zrank(key, value)
client.zrevrank(key, value)
client.zrange(key, start, end)
client.zrevrange(key, start, end)
client.zrangebyscore(key, min, max)
client.zcard(key)
client.zscore(key, element)
client.zremrangebyrank(key, min, max)
client.zremrangebyscore(key, min, max)
client.zunionstore(dstkeyN, key1,…,keyN, WEIGHTS w1,…wN, AGGREGATE SUM|MIN|MAX)

hash型別操作

client.hset(key, field, value)
client.hget(key, field)
client.hmget(key, field1, …,field N)
client.hmset(key, field1, value1,…,field N, value N)
client.hincrby(key, field, integer)
client.hexists(key, field)
client.hdel(key, field)
client.hlen(key)
client.hkeys(key)
client.hvals(key)
client.hgetall(key)

相關文章