阿里雲Redis開發規範

https://yq.aliyun.com/articles/531067#comment

1、鍵值設計

1. key名設計

  • (1)【建議】: 可讀性和可管理性

以業務名(或數據庫名)爲前綴(防止key衝突),用冒號分隔,好比業務名:表名:idjavascript

ugc:video:1
  • (2)【建議】:簡潔性

保證語義的前提下,控制key的長度,當key較多時,內存佔用也不容忽視,例如:php

user:{uid}:friends:messages:{mid}簡化爲u:{uid}:fr:m:{mid}。
  • (3)【強制】:不要包含特殊字符

反例:包含空格、換行、單雙引號以及其餘轉義字符css

2. value設計

  • (1)【強制】:拒絕bigkey(防止網卡流量、慢查詢)

string類型控制在10KB之內,hash、list、set、zset元素個數不要超過5000。java

反例:一個包含200萬個元素的list。git

非字符串的bigkey,不要使用del刪除,使用hscan、sscan、zscan方式漸進式刪除,同時要注意防止bigkey過時時間自動刪除問題(例如一個200萬的zset設置1小時過時,會觸發del操做,形成阻塞,並且該操做不會不出如今慢查詢中(latency可查)),查找方法刪除方法github

  • (2)【推薦】:選擇適合的數據類型。

例如:實體類型(要合理控制和使用數據結構內存編碼優化配置,例如ziplist,但也要注意節省內存和性能之間的平衡)redis

反例:算法

set user:1:name tom set user:1:age 19 set user:1:favor football

正例:sql

hmset user:1 name tom age 19 favor football

3.【推薦】:控制key的生命週期,redis不是垃圾桶。

建議使用expire設置過時時間(條件容許能夠打散過時時間,防止集中過時),不過時的數據重點關注idletime。數據庫

2、命令使用

1.【推薦】 O(N)命令關注N的數量

例如hgetall、lrange、smembers、zrange、sinter等並不是不能使用,可是須要明確N的值。有遍歷的需求可使用hscan、sscan、zscan代替。

2.【推薦】:禁用命令

禁止線上使用keys、flushall、flushdb等,經過redis的rename機制禁掉命令,或者使用scan的方式漸進式處理。

3.【推薦】合理使用select

redis的多數據庫較弱,使用數字進行區分,不少客戶端支持較差,同時多業務用多數據庫實際仍是單線程處理,會有干擾。

4.【推薦】使用批量操做提升效率

原生命令:例如mget、mset。
非原生命令:可使用pipeline提升效率。

但要注意控制一次批量操做的元素個數(例如500之內,實際也和元素字節數有關)。

注意二者不一樣:

1. 原生是原子操做,pipeline是非原子操做。 2. pipeline能夠打包不一樣的命令,原生作不到 3. pipeline須要客戶端和服務端同時支持。

5.【建議】Redis事務功能較弱,不建議過多使用

Redis的事務功能較弱(不支持回滾),並且集羣版本(自研和官方)要求一次事務操做的key必須在一個slot上(可使用hashtag功能解決)

6.【建議】Redis集羣版本在使用Lua上有特殊要求:

  • 1.全部key都應該由 KEYS 數組來傳遞,redis.call/pcall 裏面調用的redis命令,key的位置,必須是KEYS array, 不然直接返回error,"-ERR bad lua script for redis cluster, all the keys that the script uses should be passed using the KEYS array"
  • 2.全部key,必須在1個slot上,不然直接返回error, "-ERR eval/evalsha command keys must in same slot"

7.【建議】必要狀況下使用monitor命令時,要注意不要長時間使用。

3、客戶端使用

1.【推薦】

避免多個應用使用一個Redis實例

正例:不相干的業務拆分,公共數據作服務化。

2.【推薦】

使用帶有鏈接池的數據庫,能夠有效控制鏈接,同時提升效率,標準使用方式:

執行命令以下:
Jedis jedis = null; try { jedis = jedisPool.getResource(); //具體的命令 jedis.executeCommand() } catch (Exception e) { logger.error("op key {} error: " + e.getMessage(), key, e); } finally { //注意這裏不是關閉鏈接,在JedisPool模式下,Jedis會被歸還給資源池。 if (jedis != null) jedis.close(); }

下面是JedisPool優化方法的文章:

3.【建議】

高併發下建議客戶端添加熔斷功能(例如netflix hystrix)

4.【推薦】

設置合理的密碼,若有必要可使用SSL加密訪問(阿里雲Redis支持)

5.【建議】

根據自身業務類型,選好maxmemory-policy(最大內存淘汰策略),設置好過時時間。

默認策略是volatile-lru,即超過最大內存後,在過時鍵中使用lru算法進行key的剔除,保證不過時數據不被刪除,可是可能會出現OOM問題。

其餘策略以下:
  • allkeys-lru:根據LRU算法刪除鍵,無論數據有沒有設置超時屬性,直到騰出足夠空間爲止。
  • allkeys-random:隨機刪除全部鍵,直到騰出足夠空間爲止。
  • volatile-random:隨機刪除過時鍵,直到騰出足夠空間爲止。
  • volatile-ttl:根據鍵值對象的ttl屬性,刪除最近將要過時數據。若是沒有,回退到noeviction策略。
  • noeviction:不會剔除任何數據,拒絕全部寫入操做並返回客戶端錯誤信息"(error) OOM command not allowed when used memory",此時Redis只響應讀操做。

4、相關工具

1.【推薦】:數據同步

redis間數據同步可使用:redis-port

2.【推薦】:big key搜索

redis大key搜索工具

3.【推薦】:熱點key尋找(內部實現使用monitor,因此建議短期使用)

facebook的redis-faina

阿里雲Redis已經在內核層面解決熱點key問題,歡迎使用。

五 附錄:刪除bigkey

1. 下面操做可使用pipeline加速。 2. redis 4.0已經支持key的異步刪除,歡迎使用。
1. Hash刪除: hscan + hdel
public void delBigHash(String host, int port, String password, String bigHashKey) { Jedis jedis = new Jedis(host, port); if (password != null && !"".equals(password)) { jedis.auth(password); } ScanParams scanParams = new ScanParams().count(100); String cursor = "0"; do { ScanResult<Entry<String, String>> scanResult = jedis.hscan(bigHashKey, cursor, scanParams); List<Entry<String, String>> entryList = scanResult.getResult(); if (entryList != null && !entryList.isEmpty()) { for (Entry<String, String> entry : entryList) { jedis.hdel(bigHashKey, entry.getKey()); } } cursor = scanResult.getStringCursor(); } while (!"0".equals(cursor)); //刪除bigkey jedis.del(bigHashKey); }
2. List刪除: ltrim
public void delBigList(String host, int port, String password, String bigListKey) { Jedis jedis = new Jedis(host, port); if (password != null && !"".equals(password)) { jedis.auth(password); } long llen = jedis.llen(bigListKey); int counter = 0; int left = 100; while (counter < llen) { //每次從左側截掉100個 jedis.ltrim(bigListKey, left, llen); counter += left; } //最終刪除key jedis.del(bigListKey); }
3. Set刪除: sscan + srem
public void delBigSet(String host, int port, String password, String bigSetKey) { Jedis jedis = new Jedis(host, port); if (password != null && !"".equals(password)) { jedis.auth(password); } ScanParams scanParams = new ScanParams().count(100); String cursor = "0"; do { ScanResult<String> scanResult = jedis.sscan(bigSetKey, cursor, scanParams); List<String> memberList = scanResult.getResult(); if (memberList != null && !memberList.isEmpty()) { for (String member : memberList) { jedis.srem(bigSetKey, member); } } cursor = scanResult.getStringCursor(); } while (!"0".equals(cursor)); //刪除bigkey jedis.del(bigSetKey); }
4. SortedSet刪除: zscan + zrem
public void delBigZset(String host, int port, String password, String bigZsetKey) { Jedis jedis = new Jedis(host, port); if (password != null && !"".equals(password)) { jedis.auth(password); } ScanParams scanParams = new ScanParams().count(100); String cursor = "0"; do { ScanResult<Tuple> scanResult = jedis.zscan(bigZsetKey, cursor, scanParams); List<Tuple> tupleList = scanResult.getResult(); if (tupleList != null && !tupleList.isEmpty()) { for (Tuple tuple : tupleList) { jedis.zrem(bigZsetKey, tuple.getElement()); } } cursor = scanResult.getStringCursor(); } while (!"0".equals(cursor)); //刪除bigkey jedis.del(bigZsetKey); }
相關文章
相關標籤/搜索