本文介紹了在使用阿裡雲Redis的開發規範,從鍵值設計、指令使用、用戶端使用、相關工具等方面進行說明,通過本文的介紹可以減少使用Redis過程帶來的問題。
鍵值設計
key名設計
可讀性和可管理性
以業務名(或資料庫名)為字首(防止key沖突),用冒号分隔,比如業務名:表名:id
ugc:video:1
簡潔性
保證語義的前提下,控制key的長度,當key較多時,記憶體占用也不容忽視,例如:
user:{uid}:friends:messages:{mid}簡化為u:{uid}
不要包含特殊字元
反例:包含空格、換行、單雙引号以及其他轉義字元
value設計
拒絕bigkey(防止網卡流量、慢查詢)
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
控制key的生命周期,redis不是垃圾桶。
建議使用expire設定過期時間(條件允許可以打散過期時間,防止集中過期),不過期的資料重點關注idletime。
指令使用
O(N)指令關注N的數量
例如hgetall、lrange、smembers、zrange、sinter等并非不能使用,但是需要明确N的值。有周遊的需求可以使用hscan、sscan、zscan代替。
禁用指令
禁止線上使用keys、flushall、flushdb等,通過redis的rename機制禁掉指令,或者使用scan的方式漸進式處理。
合理使用select
redis的多資料庫較弱,使用數字進行區分,很多用戶端支援較差,同時多業務用多資料庫實際還是單線程處理,會有幹擾。
使用批量操作提高效率
- 原生指令:例如mget、mset。
- 非原生指令:可以使用pipeline提高效率。
但要注意控制一次批量操作的元素個數(例如500以内,實際也和元素位元組數有關)。
注意兩者不同:
- 原生是原子操作,pipeline是非原子操作。
- pipeline可以打包不同的指令,原生做不到
- pipeline需要用戶端和服務端同時支援。
不建議過多使用Redis事務功能
Redis的事務功能較弱(不支援復原),而且叢集版本(自研和官方)要求一次事務操作的key必須在一個slot上(可以使用hashtag功能解決)。
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 arrayrn"
2、所有key,必須在1個slot上,否則直接傳回error, "-ERR eval/evalsha command keys must in same slotrn"
monitor指令
必要情況下使用monitor指令時,要注意不要長時間使用。
用戶端使用
避免多個應用使用一個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隻響應讀操作。
相關工具
資料同步
redis間資料同步可以使用:redis-port
big key搜尋
redis大key搜尋工具:https://developer.aliyun.com/article/117042
熱點key尋找
内部實作使用monitor,是以建議短時間使用facebook的redis-faina 阿裡雲Redis已經在核心層面解決熱點key問題
删除bigkey
- 下面操作可以使用pipeline加速。
- 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);
}
連結:https://developer.aliyun.com/article/531067