Redis能夠存儲鍵與5種不一樣數據結構類型之間的映射,這5種數據結構類型分別爲string(字符串),list(列表),set(集合),hash(散列),zset(有序集合),下面將分別對這5種數據類型的控制命令進行總結,熟話說好記性不如爛筆頭,方便之後查看。html
Redis種的字符串有三種類型的值:字節,整數和浮點數redis
(1)命令列表數據結構
SET:SET key value ------設置存儲在給定鍵種的值app
GET:GET key value ------獲取存儲在給定鍵種的值ide
DEL:DEL key ------刪除存儲在給定鍵種的值(這個命令能夠用於全部類型)post
INCR:INCR key ------將鍵對應的值加1測試
DECR:DECR key ------將鍵對應的值減1spa
INCRBY:incrby key number ------將鍵對應的值加numbercode
DECRBY:decrby key number ------將鍵對應的值減numberorm
APPEND:append key value ------將值value追加到給定鍵key當前村粗的值的末尾
GETRANGE:getrange key start end ------獲取從start到end範圍內的字串
SETRANGE:setrange key offset val ------將從offset偏移量開始的字串設置指定值val
GETBIT:getbit key offset ------返回位串中偏移量爲offset的二進制位值
SETBIT:setbit key offset val ------位串中偏移量爲offset的二進制位值設置爲val
BITCOUNT:biitcount key [start end] ------統計二進制位串裏面值位1的二進制位數量
BITOP:bitop operation dest-key key1 [key2...] ------對一個或多個二進制位串執行包括並、或、異或、非在內的任意一種位運算操做
(2)示例
redis 127.0.0.1:6379> set name zhangsan OK redis 127.0.0.1:6379> set age 18 OK redis 127.0.0.1:6379> get name "zhangsan" redis 127.0.0.1:6379> get age "18" redis 127.0.0.1:6379> incr age (integer) 19 redis 127.0.0.1:6379> decr age (integer) 18 redis 127.0.0.1:6379> incrby age 5 (integer) 23 redis 127.0.0.1:6379> decrby age 5 (integer) 18 redis 127.0.0.1:6379> append name _lisi (integer) 13 redis 127.0.0.1:6379> get name "zhangsan_lisi" redis 127.0.0.1:6379> getrange name 1 0 "" redis 127.0.0.1:6379> getrange name 0 -1 "zhangsan_lisi" redis 127.0.0.1:6379> setrange name 0 wangmazi (integer) 13 redis 127.0.0.1:6379> get name "wangmazi_lisi" redis 127.0.0.1:6379> del name (integer) 1 redis 127.0.0.1:6379> get name (nil)
(3)注意事項
a. 若是對一個不存在的鍵或者一個保存了空串的鍵執行自增或自減操做,那麼Redis在執行操做時會將這個鍵的值看成0來處理
b. 即便在設置鍵時輸入的值位字符串,但只要這個值能夠能夠被理解爲整數,就能夠看成整數來處理
c. GETRANGE命令由之前的SUBSET命令更名而來的,若是是2.6或以上redis版本,使用getrange()方法來獲取字串
(1)一些經常使用的列表命令
RPUSH:rpush key value [value1...] ------將一個或多個值添加到列表的右端
LPUSH:lpush key value [value1...] ------將一個或多個值添加到列表的左端
RPOP:rpop key ------移除並返回列表最右端的元素
LPOP:lpop key ------移除並返回列表最左端的元素
LINDEX:lindex key offset --------返回列表中偏移量爲offset的元素
LRANGE:lrange key start end ------返回列表中偏移量在[satrt,end]範圍內的元素,包括satrt和end
LTRIM:ltrim key start end ------對列表進行修剪,只保留從start到end範圍內的元素,包括start和end
redis 127.0.0.1:6379> rpush key 1,2,3 (integer) 1 redis 127.0.0.1:6379> lpush key 4,5,6 (integer) 2 redis 127.0.0.1:6379> lrange key 0 -1 1) "4,5,6" 2) "1,2,3" redis 127.0.0.1:6379> rpush key hello (integer) 3 redis 127.0.0.1:6379> lrange key 0 -1 1) "4,5,6" 2) "1,2,3" 3) "hello" redis 127.0.0.1:6379> lindex key 2 "hello" redis 127.0.0.1:6379> ltrim key 1 2 OK redis 127.0.0.1:6379> lrange key 0 -1 1) "1,2,3" 2) "hello"
(2)阻塞式的列表彈出命令以及在列表之間元素的移動
BLPOP blpop key1 [key2...] timeout ------從一個非空列表中彈出位於最左端的元素,或者在timeout秒以內阻塞並等待可彈出的元素
BRPOP
BPOPLPUSH bpoplpush source-key dest-key ------從原始列表彈出最右端的元素並壓入目標列表左端,並返回這個元素
BRPOPLPUSH BRPOPLPUSH source-key dest-key timeout ------從原始列表彈出最右端的元素並壓入目標列表左端,並返回這個元素,若是source-key爲空阻塞等待
Redis的集合以無序的方式來存儲多個各不相同的元素,能夠快速的對集合進行添加,刪除、元素檢查、組合和關聯等操做
(1)經常使用集合命令
SADD:sadd key item [item...] ------將一個或多個元素添加到集合中
SREM:srem key item [item...] ------從集合中移除一個或多個元素
SISMEMBER:sismember key item ------檢查item是否存在於集合key裏面
SCARD:scard key ------返回集合包含的元素的數量
SMEMBERS:smembers key ------返回集合包含的全部元素
SRANDMEMBER:srandmember key [count] ------從集合裏隨機的返回一個或多個元素
SPOP:spop key ------隨機地移除幾個中的一個元素,並返回被移除的元素
SMOVE:smove source-key dest-key item ------若是原集合包含item,從原集合移除item並將item添加到集合目標集合,成功返回1,不然返回0
(2)示例
redis 127.0.0.1:6379> sadd key 1 2 3 (integer) 3 redis 127.0.0.1:6379> smembers key 1) "1" 2) "2" 3) "3" redis 127.0.0.1:6379> sadd key 3 (integer) 0 redis 127.0.0.1:6379> scard key (integer) 3 redis 127.0.0.1:6379> srem key 3 (integer) 1 redis 127.0.0.1:6379> smembers key 1) "1" 2) "2" redis 127.0.0.1:6379> srandmember key "2" redis 127.0.0.1:6379> smembers key 1) "1" 2) "2" redis 127.0.0.1:6379> spop key "1" redis 127.0.0.1:6379> smembers key 1) "2"
(2)組合和關聯命令
SDIFF:sdiff key1 [key2...] ------返回那些存在於第一集合key1,但不存在於其餘集合中的元素
SDIFFSTORE:sdiffstore dest-key key1 [key2...] -------將SDIFF的結果存到目標集合中
SINTER:sinter key1 [key2...] ------返回那些同時存在於全部集合中的元素
SINTERSTORE:sinterstore dest-key key1 [key2] ------將SINTER的結果放到目標集合中
SUNION:sunion key1 [key2...] ------返回那些至少存在於一個集合中的元素
SUNIONSTORE:sunionstore dest-key key1 [key2...] ------將SUNION的結果放到表集合中
(3)示例
redis 127.0.0.1:6379> sadd key1 a b c d e (integer) 5 redis 127.0.0.1:6379> sadd key2 c d e f (integer) 4 redis 127.0.0.1:6379> smembers key1 1) "c" 2) "d" 3) "e" 4) "a" 5) "b" redis 127.0.0.1:6379> smembers key2 1) "c" 2) "d" 3) "e" 4) "f" redis 127.0.0.1:6379> sdiff key1 key2 1) "a" 2) "b" redis 127.0.0.1:6379> sinter key1 key2 1) "c" 2) "d" 3) "e" redis 127.0.0.1:6379> sunion key1 key 2 1) "c" 2) "d" 3) "a" 4) "e" 5) "b"
Redis的散列將多個鍵值對存儲在Redis的鍵裏面
(1)散列經常使用命令
HSET:hset key-name key value ------爲散列添加鍵值對
HGET:hget key-name key ------獲得散列的鍵值對
HMSET:hmset key-name key value [key name...] -------爲散列設置一個或多個鍵值對
HMGET:hmget key-name key [key...] ------獲得散列的一個或多個鍵值對
HDEL:hdel key-name key [key...] ------刪除散列裏面的一個或多個鍵值對
HLEN:hlen key-name ------返回散列包含的鍵值對數量
HEXISTS:hexists key-name key ------檢查鍵值是否在散列中
HKEYS:hkeys key-name ------獲得散列的全部鍵值
HVALS:hvals key-name ------獲得散列的全部鍵對應的值
HGETALL:hgetall key-name ------獲得散列的說有鍵值對
HINCRBY:hincrby key-name key number ------將鍵key的值加上整數number
HINCRBYFLOAT:hincrbyfloat key-name key number ------將鍵key的值加上浮點數number
(2)示例
redis 127.0.0.1:6379> hmset person name zhangsan age 17 OK redis 127.0.0.1:6379> hmget person name age 1) "zhangsan" 2) "17" redis 127.0.0.1:6379> hset person sex man (integer) 1 redis 127.0.0.1:6379> hlen person (integer) 3 redis 127.0.0.1:6379> hgetall person 1) "name" 2) "zhangsan" 3) "age" 4) "17" 5) "sex" 6) "man" redis 127.0.0.1:6379> hkeys person 1) "name" 2) "age" 3) "sex" redis 127.0.0.1:6379> hvals person 1) "zhangsan" 2) "17" 3) "man" redis 127.0.0.1:6379> hincrby person age 8 (integer) 25 redis 127.0.0.1:6379> hget person age "25"
和散列存儲着鍵與值之間的映射相似,有序集合也存儲着成員與分值之間的映射,而且提供了分值處理命令,以及和根據分值大小有序地獲取或掃描成員和分值的命令
(1)常有有序集合命令
ZADD:zadd key-name score number [score number...] ------將帶有分值的成員添加到有序集合
ZREM:arem key-name number [number...] ------從有序集合裏面移除指定的成員,並返回被移除成員的數量
ZCARD:zcard key-name ------返回有序集合包含的成員數量
ZINCRBY:zincrby key-name increment number ------將number成員的分值加上increment
ZCOUNT:zcount key-name min max ------返回分值介於min和max之間的成員數量
ZRANK:zrank key-name merber ------返回成員member在有序集合中的排名
ZRANGE:zrange key-name start stop [withscores] ------返回排名介於start和stop之間的成員,若是給定了withscores則分值一塊兒返回
ZSCORE:zscore key-name number ------返回成員number的分值
(2)示例
redis 127.0.0.1:6379> zadd ages 19 person1 20 person2 30 person3 (integer) 3 redis 127.0.0.1:6379> zcard ages (integer) 3 redis 127.0.0.1:6379> zcount ages 0 40 (integer) 3 redis 127.0.0.1:6379> zrange ages 0 40 withscores 1) "person1" 2) "19" 3) "person2" 4) "20" 5) "person3" 6) "30" redis 127.0.0.1:6379> zscore ages person2 "20" redis 127.0.0.1:6379> zincrby ages 10 person3 "40" redis 127.0.0.1:6379> zscore ages person3 "40" redis 127.0.0.1:6379> zincrby ages -10 person3 "30" redis 127.0.0.1:6379> zscore ages person3 "30"
(3)有序集合更高級命令
ZREVRANK:zrevrank key-name number ------返回有序集合裏成員number的排名,按照分值從大到小的排列
ZREVRANGE:zrevrange key-name start stop [withscores] ---- 返回zrange的反序內容
ZREVRANGEBYSCORE:zrevrangebyscore key-name min max [withscores] [limit offset count] ------返回有序集合中,分值介於min和max之間的全部成員,並按照分值大小的順序返回
ZREMRANGEBYRANK:zremrangebyrank key-name satrt stop ------移除有序集合中排名介於satrt和stop之間的全部成員
ZREMRANGEBYSCORE:zremrangebyscore key-name min max ------移除有序集合中分值介於satrt和stop之間的全部成員
ZINTERSTORE:zinterstore dest-key key-count key1 [key2...] [WEIGHTS weight [weight...]] [AGGREGATE SUM|MIN|MAX] ------對給定的有序集合執行相似集合的交集運算
ZUNIONSTORE:zunionstore dest-key key-count key1 [key2...] [WEIGHTS weight [weight...]] [AGGREGATE SUM|MIN|MAX] ------對給定的有序集合執行相似集合的並集運算
(4)示例
redis 127.0.0.1:6379> zrank ages person1 (integer) 0 redis 127.0.0.1:6379> zrevrank ages person1 (integer) 2 redis 127.0.0.1:6379> zrevrange ages 0 40 withscores 1) "person3" 2) "30" 3) "person2" 4) "20" 5) "person1" 6) "19" redis 127.0.0.1:6379> zcard ages (integer) 3 redis 127.0.0.1:6379> zrevrangebyscore ages 40 0 withscores 1) "person3" 2) "30" 3) "person2" 4) "20" 5) "person1" 6) "19"
發佈(publish)與訂閱(subscribe)的特色是訂閱者負責訂閱頻道(channel),發送者負責向頻道發送二進制字符串消息,每當由消息被髮送到給定頻道時,頻道的全部訂閱者都會收到消息。
SUBSCRIBE:subscribe channel [channel] ------訂閱給定的一個或多個頻道
UNSUBSCRIBE:unsubcribe channel [channel] ------退訂給定的一個或多個頻道
PUBLISH:publish channel [channel...] ------向給定頻道發送消息
PSUBSCRIBE:psubscribe pattern [pattern] ------訂閱與給定模式相匹配的全部頻道
PUNSUBSCRIBE:punsubscribe pattern [pattern] ------退訂給定的模式,若是執行時沒有給定任何模式,那退訂全部模式
簡單示例:實現文章發佈,獲取和投票
(1)文章發佈
ONE_WEEK_IN_SECOND = 7*24*60*60 def post_article(conn, user, title, link): '''文章發佈,實現如下操做: (1) 獲取文章id (2) 初始化集合管理已投票用戶 (3) 初始化文章信息散列表 (4) 初始化分數有序集合 (5) 初始化時間有序集合 ''' article_id = str(conn.incr('article:')) #獲得文章id voted_key = 'voted:' + article_id #已投票集合key conn.sadd(voted_key,user) #建立集合管理已投票用戶,本身不容許投票 conn.expire(voted_key,ONE_WEEK_IN_SECOND) #設置鍵的過時時間 now = time.time() article_key = 'article:' + article_id #文章信息散列key # 初始化文章信息散列表 conn.hmset(article_key, { 'title':title, 'link:':link, 'poster':user, 'time':now, 'votes':1}) # 初始化分數有序集合 conn.zadd('score:', {article_key:now+VOTE_SCORE}) # 初始化時間有序集合 conn.zadd('time:', {article_key:now}) return article_id
(2)文章獲取
def get_articles(conn, page, order='score:'): '''默認根據分數排名獲取指定頁的文章信息''' #設定每頁文章數目 ARTICLES_PER_PAGE = 5 start = (page-1)*ARTICLES_PER_PAGE end = start + (ARTICLES_PER_PAGE -1) ids = conn.zrange(order, start, end) articles = [] for id in ids: article_data = conn.hgetall(id) article_data['id'] = id articles.append(article_data) return articles
(3)投票
def article_vote(conn, id, user): '''對文章進行投票,投票規則: (1)投票的有效期時間爲1周 (1)一篇文章一週內用戶只容許投一次票 (2)分數計算方式爲每投一次票加432分 ''' VOTE_SCORE = 432 # 根據文章ID獲取文章的發佈時間,判斷是否在投票的有效期內 article_key = 'article:' + id publish_time = conn.zcore('time:', article_key) if publish_time + ONE_WEEK_IN_SECOND < time.time(): return else: #用戶能夠投票,用戶完成投票後將該用戶添加到已投票用戶管理集合 voted_key = 'voted:' + id if conn.sadd(voted_key, user): #更新score:有序集合列表分數 conn.zincrby('socre:',article_key, VOTE_SCORE) #更新散列表文章信息 conn.hincr(article_key, 'votes')
(4)對文章獲取進行測試
if __name__ == '__main__': try: conn = redis.Redis() except: raise 'connect exception' else: post_article(conn,'fate0729','Redis train','https://www.cnblogs.com/') post_article(conn,'fate0729','Redis train','https://www.cnblogs.com/') post_article(conn,'fate0729','Redis train','https://www.cnblogs.com/') post_article(conn,'fate0729','Redis train','https://www.cnblogs.com/') post_article(conn,'fate0729','Redis train','https://www.cnblogs.com/') post_article(conn,'fate0729','Redis train','https://www.cnblogs.com/') articles = get_articles(conn, 0) for article in articles: print('-----article--------') for key, val in article.items(): if isinstance(key,bytes): print('{}:{}'.format(key.decode(encoding='utf-8'),val.decode('utf-8'))) else: print('{}:{}'.format(key,val.decode('utf-8')))
輸出:
文章同步發佈: https://www.geek-share.com/detail/2755069520.html
參考文章: