一份完整的阿里雲 Redis 開發規範,值得收藏!

來源:yq.aliyun.com/articles/531067redis

做者:付磊-起揚 算法

 

本文主要介紹在使用阿里雲Redis的開發規範,從下面幾個方面進行說明。數據庫

  • 鍵值設計數組

  • 命令使用微信

  • 客戶端使用數據結構

  • 相關工具併發

經過本文的介紹能夠減小使用Redis過程帶來的問題。dom

1、鍵值設計

一、key名設計

可讀性和可管理性

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

  1. ugc:video:1ide

簡潔性

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

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

不要包含特殊字符

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

二、value設計

拒絕bigkey

防止網卡流量、慢查詢,string類型控制在10KB之內,hash、list、set、zset元素個數不要超過5000。

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

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

選擇適合的數據類型

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

反例:

  1. set user:1:name tom

  2. set user:1:age 19

  3. set user:1:favor football

正例:

  1. hmset user:1 name tom age 19 favor football

控制key的生命週期

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

2、命令使用

一、O(N)命令關注N的數量

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

二、禁用命令

禁止線上使用keys、flushall、flushdb等,經過redis的rename機制禁掉命令,或者使用scan的方式漸進式處理。一個致命的 Redis 命令,致使公司損失 400 萬!!關注Java技術棧微信公衆號,在後臺回覆關鍵字:redis,能夠獲取更多棧長整理的 Redis 系列技術乾貨。

三、合理使用select

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

四、使用批量操做提升效率
  1. 原生命令:例如mget、mset。

  2. 非原生命令:可使用pipeline提升效率。

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

注意二者不一樣:

  1. 原生是原子操做,pipeline是非原子操做。

  2. pipeline能夠打包不一樣的命令,原生作不到

  3. pipeline須要客戶端和服務端同時支持。

五、不建議過多使用Redis事務功能

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

六、Redis集羣版本在使用Lua上有特殊要求

一、全部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 arrayrn" 二、全部key,必須在1個slot上,不然直接返回error, "-ERR eval/evalsha command keys must in same slotrn"

七、monitor命令

必要狀況下使用monitor命令時,要注意不要長時間使用。

3、客戶端使用

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

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

二、使用鏈接池

能夠有效控制鏈接,同時提升效率,標準使用方式:

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();
}
三、熔斷功能

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

四、合理的加密

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

五、淘汰策略

根據自身業務類型,選好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、相關工具

一、數據同步

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

二、big key搜索

redis大key搜索工具

三、熱點key尋找

內部實現使用monitor,因此建議短期使用facebook的redis-faina 阿里雲Redis已經在內核層面解決熱點key問題

5、刪除bigkey

  1. 下面操做可使用pipeline加速。

  2. redis 4.0已經支持key的異步刪除,歡迎使用。

一、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);
}
二、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);
}
三、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);
}
四、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);}
相關文章
相關標籤/搜索