1. 程式人生 > >Redis入門很簡單之二【常見操作命令】

Redis入門很簡單之二【常見操作命令】

哈希表 shu 分享 排序。 sca ann mongodb pin set

Redis入門很簡單之二【常見操作命令】

博客分類:
  • NoSQL/Redis/MongoDB
redisnosql緩存

Redis提供了豐富的命令,允許我們連接客戶端對其進行直接操作.這裏簡單介紹一下作為常用的一些命令,包括對字符串、列表、集合、有序集合、哈希表的操作,以及一些其他常用命令。


【 基本操作】

1. 添加記錄:通常用於設置字符串(string)類型,或者整數類型;如果key已經存在,則覆蓋其對應的值。

Shell代碼 技術分享
  1. set name James

2. 獲取記錄:通過鍵獲取值。

Shell代碼 技術分享
  1. get name

3. 遞增/遞減:針對整數類型,仍然使用類似於字符串的操作方式:並且可以進行遞增、遞減操作。

Shell代碼 技術分享
  1. set age 22
  2. incr age
  3. decr age

4. 在key不存在時才添加:

Shell代碼 技術分享
  1. setnx name Nick

5. 設置失效時間:以避免數據量的持續增長,如下命令:設置過期時間為5s。

Shell代碼 技術分享
  1. setex name 5 Bill

上述命令,等價於:

Shell代碼 技術分享
  1. set name Bill
  2. expire name 5


【列表操作】可以使用列表(list)來模擬隊列(queue)/堆棧(stack)。
1. 添加元素:給列表userList從右邊壓入字符串James。

Shell代碼 技術分享
  1. rpush userList James

2. 移除元素:從userList左側移除第一個元素。

Shell代碼 技術分享
  1. lpop userList

3. 列表範圍:如下命令獲取從0(左側起始位置)到-1(右側最後一個位置)之間的所有元素,並且包含起始位置的元素。

Shell代碼 技術分享
  1. lrange userList 0 -1

4. 設置元素:設置userList位置1處為新值,對包含空格的字符串使用引號括起來。

Shell代碼 技術分享
  1. lset userList 1 "Nick Xu"

5. 列表長度:

Shell代碼 技術分享
  1. llen userList

6. 裁剪列表:執行如下命令後,列表userList只包含原始列表從位置1到3的連續元素。

Shell代碼 技術分享
  1. ltrim userList 1 3

【集合操作】集合中元素不能重復,並且集合是無序的。
1. 添加元素:可同時添加多個元素。

Shell代碼 技術分享
  1. sadd fruit watermelon
  2. sadd fruit apple pear

2. 查看集合中的所有元素:

Shell代碼 技術分享
  1. smembers fruit

3. 移除元素:

Shell代碼 技術分享
  1. srem fruit apple

4. 集合大小:返回集合中包含的元素的個數。

Shell代碼 技術分享
  1. scard fruit

5. 集合中是否包含元素:

Shell代碼 技術分享
  1. sismember fruit pear

6. 集合的運算:如下命令返回集合food和fruit的並集,另外還有交集(sinter)、差集(sdiff)運算。

Shell代碼 技術分享
  1. sunion food fruit

【有序集合】sorted set
1. 添加元素:根據第二個參數進行排序。

Shell代碼 技術分享
  1. zadd user 23 James

2. 重復添加:存在相同的value,權重參數更新為24。

Shell代碼 技術分享
  1. zadd user 24 James

3. 集合範圍:找到從0到-1的所有元素,並且是有序的。

Shell代碼 技術分享
  1. zrange user 0 -1

【哈希表操作】

1. 添加元素:給哈希表china添加鍵為shannxi,值為xian的成員。

Shell代碼 技術分享
  1. hset china shannxi xian

2. 獲取元素:獲取哈希表china中鍵shannxi所對應的value值。

Shell代碼 技術分享
  1. hget china shannxi

3. 返回哈希表所有的key:

Shell代碼 技術分享
  1. hkeys china

4. 返回哈希表所有的value:

Shell代碼 技術分享
  1. hvals china

【補充:對key的操作】

1. 刪除key:

Shell代碼 技術分享
  1. del name

2. key是否存在:

Shell代碼 技術分享
  1. exists name

3. key的存活時間:time to live

Shell代碼 技術分享
  1. ttl name

4. 查詢所有的key:

Shell代碼 技術分享
  1. keys *

5. 模糊匹配:

Shell代碼 技術分享
  1. keys name*

6. 將key移動到數據庫1中:

Shell代碼 技術分享
  1. move name 1


【其他命令】
1. 獲取服務器信息:

Shell代碼 技術分享
  1. info

2. 獲取特定信息:

Shell代碼 技術分享
  1. info keyspace

3. 選擇數據庫:在Redis中默認有16個數據庫(編號從0到15),默認是對數據庫0進行操作。

Shell代碼 技術分享
  1. select 1

4. 當前數據庫中key的數據:

Shell代碼 技術分享
  1. dbsize

5. 清空當前數據庫:

Shell代碼 技術分享
  1. flushdb

6. 清空所有數據庫:

Shell代碼 技術分享
  1. flushall

7. 測試連接:返回pong即為連接暢通。

Shell代碼 技術分享
  1. ping

8. 退出客戶端:或者是exit 命令。

Shell代碼 技術分享
  1. quit

9. 關閉服務器:

Shell代碼 技術分享
  1. shutdown

Redis入門很簡單之二【常見操作命令】