阿里雲 Redis 開發規範

摘要:本文介紹了在使用阿里雲 Redis 的開發規範,從鍵值設計、命令使用、客戶端使用、相關工具等方面進行說明,通過本文的介紹可以減少使用 Redis 過程帶來的問題。

一、鍵值設計

1. key 名設計

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

ugc:video:1

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

user:{uid}:friends:messages:{mid}簡化爲u:{uid}:fr:m:{mid}

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

2. value 設計

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

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

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

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

反例:

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

正例:

hmset user:1 name tom age 19 favor football

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

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

二、命令使用

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

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

2.【推薦】:禁用命令

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

3.【推薦】合理使用 select

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

4.【推薦】使用批量操作提高效率

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

注意兩者不同:

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

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

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

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

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

三、客戶端使用

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 問題。

其他策略如下:

四、相關工具

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);
}

作者:carlosfu, 本文版權歸作者所有

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

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/4CskATveVkzGliqXiZ1Wpw